Esempio n. 1
0
static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
                              const char *filename, PRBool cacert)
{
  CURLcode err = (cacert)
    ? CURLE_SSL_CACERT_BADFILE
    : CURLE_SSL_CERTPROBLEM;

  /* libnsspem.so leaks memory if the requested file does not exist.  For more
   * details, go to <https://bugzilla.redhat.com/734760>. */
  if(is_file(filename))
    err = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);

  if(CURLE_OK == err && !cacert) {
    /* we have successfully loaded a client certificate */
    CERTCertificate *cert;
    char *nickname = NULL;
    char *n = strrchr(filename, '/');
    if(n)
      n++;

    /* The following undocumented magic helps to avoid a SIGSEGV on call
     * of PK11_ReadRawAttribute() from SelectClientCert() when using an
     * immature version of libnsspem.so.  For more details, go to
     * <https://bugzilla.redhat.com/733685>. */
    nickname = aprintf("PEM Token #1:%s", n);
    if(nickname) {
      cert = PK11_FindCertFromNickname(nickname, NULL);
      if(cert)
        CERT_DestroyCertificate(cert);

      free(nickname);
    }
  }

  return err;
}
Esempio n. 2
0
/* encode the torrent into a hidim with line_length and write the png to file */
int encode(const char* torrent, int line_length) {
    char *metadata;
    unsigned int length;

    if (config & CONFIG_VERBOSE) {
        printf(":: encoding %s\n", torrent);
    }

    metadata = create_metadata(&length, line_length, torrent);
    if (metadata == NULL) {
        return 0;
    }
    if (config & CONFIG_MORE_VERBOSE) {
        printf("%s\n", metadata);
    }

    unsigned int total_length = strlen(metadata) + length;
    png_uint_32 height = line_length;
    png_uint_32 width = total_length/(line_length*3) + (total_length%(line_length*3) ? 1 : 0);
    if (width < MIN_WIDTH) {
        fprintf(stderr, "Warning: %s: width of hidim(%d) is very small. Choose a smaller line length\n",
               torrent, (unsigned int)width);
    }
    if (config & CONFIG_MORE_VERBOSE) {
        printf("total_length=%d height=%u width=%u\n", total_length, (unsigned int)height, (unsigned int)width);
    }
    /* allocate memory for the image */
    png_bytep *row_pointers = calloc(height, sizeof(png_bytep));
    for (int i=0; i<height; i++) {
        row_pointers[i] = calloc(3*width, sizeof(png_byte));
    }

    /* construct pixel data from hidim data */
    agregate_data(row_pointers, height, width, line_length, length, metadata, torrent);
    free(metadata);

    /* add the hid.im logo */
    if (config & CONFIG_BORDER) {
        row_pointers = add_banner(row_pointers, &width, &height);
    }

    /* make the name of the png file */
    char *filename = get_pngfile(basename(torrent));

    /* check if file already exists */
    if (is_file(filename) && (!(config & CONFIG_OVERWRITE))) {
        fprintf(stderr, "%s already exists. nothing done.\n", filename);
        free(filename);
        free_array(row_pointers, height);
        return 0;
    }

    write_png(row_pointers, width, height, filename);
    if (config & CONFIG_VERBOSE) {
        printf("%s has been saved\n", filename);
    }
    free(filename);

    free_array(row_pointers, height);

    return 1;
}
Esempio n. 3
0
/* check_rc_files:
 * Read the file pointer specified (rootkit_files)
 * and check if the configured file is there
 */
void check_rc_files(char *basedir, FILE *fp)
{
    char buf[OS_SIZE_1024 +1];
    char file_path[OS_SIZE_1024 +1];

    char *file;
    char *name;
    char *link;

    int _errors = 0;
    int _total = 0;


    debug1("%s: DEBUG: Starting on check_rc_files", ARGV0);

    while(fgets(buf, OS_SIZE_1024, fp) != NULL)
    {
        char *nbuf;

        /* Removing end of line */
        nbuf = strchr(buf, '\n');
        if(nbuf)
        {
            *nbuf = '\0';
        }

        /* Assigning buf to be used */
        nbuf = buf;

        /* Excluding commented lines or blanked ones */
        while(*nbuf != '\0')
        {
            if(*nbuf == ' ' || *nbuf == '\t')
            {
                nbuf++;
                continue;
            }
            else if(*nbuf == '#')
                goto newline;
            else
                break;
        }

        if(*nbuf == '\0')
            goto newline;

        /* File now may be valid */
        file = nbuf;
        name = nbuf;


        /* Getting the file and the rootkit name */
        while(*nbuf != '\0')
        {
            if(*nbuf == ' ' || *nbuf == '\t')
            {
                /* Setting the limit for the file */
                *nbuf = '\0';
                nbuf++;
                break;
            }
            else
            {
                nbuf++;
            }
        }

        if(*nbuf == '\0')
            goto newline;


        /* Some ugly code to remove spaces and \t */
        while(*nbuf != '\0')
        {
           if(*nbuf == '!')
           {
               nbuf++;
               if(*nbuf == ' ' || *nbuf == '\t')
               {
                   nbuf++;
                   name = nbuf;

                   break;
               }
           }
           else if(*nbuf == ' ' || *nbuf == '\t')
           {
               nbuf++;
               continue;
           }
           else
           {
               goto newline;
           }
        }


        /* Getting the link (if present) */
        link = strchr(nbuf, ':');
        if(link)
        {
            *link = '\0';

            link++;
            if(*link == ':')
            {
                link++;
            }
        }


        /* Cleaning any space of \t at the end */
        nbuf = strchr(nbuf, ' ');
        if(nbuf)
        {
            *nbuf = '\0';
        }

        nbuf = strchr(nbuf, '\t');
        if(nbuf)
        {
            *nbuf = '\0';
        }

        _total++;


        /* Checking if it is a file to search everywhere */
        if(*file == '*')
        {
            if(rk_sys_count >= MAX_RK_SYS)
            {
                merror(MAX_RK_MSG, ARGV0, MAX_RK_SYS);
            }

            else
            {
                /* Removing * / from the file */
                file++;
                if(*file == '/')
                    file++;

                /* Memory assignment */
                rk_sys_file[rk_sys_count] = strdup(file);
                rk_sys_name[rk_sys_count] = strdup(name);

                if(!rk_sys_name[rk_sys_count] ||
                   !rk_sys_file[rk_sys_count] )
                {
                    merror(MEM_ERROR, ARGV0);

                    if(rk_sys_file[rk_sys_count])
                        free(rk_sys_file[rk_sys_count]);
                    if(rk_sys_name[rk_sys_count])
                        free(rk_sys_name[rk_sys_count]);

                    rk_sys_file[rk_sys_count] = NULL;
                    rk_sys_name[rk_sys_count] = NULL;
                }

                rk_sys_count++;

                /* Always assigning the last as NULL */
                rk_sys_file[rk_sys_count] = NULL;
                rk_sys_name[rk_sys_count] = NULL;
            }
            continue;
        }

        snprintf(file_path, OS_SIZE_1024, "%s/%s",basedir, file);

        /* Checking if file exists */
        if(is_file(file_path))
        {
            char op_msg[OS_SIZE_1024 +1];

            _errors = 1;
            snprintf(op_msg, OS_SIZE_1024, "Rootkit '%s' detected "
                     "by the presence of file '%s'.",name, file_path);

            notify_rk(ALERT_ROOTKIT_FOUND, op_msg);
        }

        newline:
            continue;
    }

    if(_errors == 0)
    {
        char op_msg[OS_SIZE_1024 +1];
        snprintf(op_msg,OS_SIZE_1024,"No presence of public rootkits detected."
                                    " Analyzed %d files.", _total);
        notify_rk(ALERT_OK, op_msg);
    }
}
Esempio n. 4
0
struct transport *transport_get(struct remote *remote, const char *url)
{
	const char *helper;
	struct transport *ret = xcalloc(1, sizeof(*ret));

	ret->progress = isatty(2);

	if (!remote)
		die("No remote provided to transport_get()");

	ret->got_remote_refs = 0;
	ret->remote = remote;
	helper = remote->foreign_vcs;

	if (!url && remote->url)
		url = remote->url[0];
	ret->url = url;

	/* maybe it is a foreign URL? */
	if (url) {
		const char *p = url;

		while (is_urlschemechar(p == url, *p))
			p++;
		if (starts_with(p, "::"))
			helper = xstrndup(url, p - url);
	}

	if (helper) {
		transport_helper_init(ret, helper);
	} else if (starts_with(url, "rsync:")) {
		ret->get_refs_list = get_refs_via_rsync;
		ret->fetch = fetch_objs_via_rsync;
		ret->push = rsync_transport_push;
		ret->smart_options = NULL;
	} else if (url_is_local_not_ssh(url) && is_file(url) && is_bundle(url, 1)) {
		struct bundle_transport_data *data = xcalloc(1, sizeof(*data));
		ret->data = data;
		ret->get_refs_list = get_refs_from_bundle;
		ret->fetch = fetch_refs_from_bundle;
		ret->disconnect = close_bundle;
		ret->smart_options = NULL;
	} else if (!is_url(url)
		|| starts_with(url, "file://")
		|| starts_with(url, "git://")
		|| starts_with(url, "ssh://")
		|| starts_with(url, "git+ssh://")
		|| starts_with(url, "ssh+git://")) {
		/* These are builtin smart transports. */
		struct git_transport_data *data = xcalloc(1, sizeof(*data));
		ret->data = data;
		ret->set_option = NULL;
		ret->get_refs_list = get_refs_via_connect;
		ret->fetch = fetch_refs_via_pack;
		ret->push_refs = git_transport_push;
		ret->connect = connect_git;
		ret->disconnect = disconnect_git;
		ret->smart_options = &(data->options);

		data->conn = NULL;
		data->got_remote_heads = 0;
	} else {
		/* Unknown protocol in URL. Pass to external handler. */
		int len = external_specification_len(url);
		char *handler = xmalloc(len + 1);
		handler[len] = 0;
		strncpy(handler, url, len);
		transport_helper_init(ret, handler);
	}

	if (ret->smart_options) {
		ret->smart_options->thin = 1;
		ret->smart_options->uploadpack = "git-upload-pack";
		if (remote->uploadpack)
			ret->smart_options->uploadpack = remote->uploadpack;
		ret->smart_options->receivepack = "git-receive-pack";
		if (remote->receivepack)
			ret->smart_options->receivepack = remote->receivepack;
	}

	return ret;
}
Esempio n. 5
0
int main(int argc, char **argv) 
{
  struct jpeg_decompress_struct dinfo;
  struct jpeg_compress_struct cinfo;
  struct my_error_mgr jcerr,jderr;
  JSAMPARRAY buf = NULL;
  jvirt_barray_ptr *coef_arrays = NULL;
  char marker_str[256];
  char tmpfilename[MAXPATHLEN],tmpdir[MAXPATHLEN];
  char newname[MAXPATHLEN], dest_path[MAXPATHLEN];
  volatile int i;
  int c,j, tmpfd, searchcount, searchdone;
  int opt_index = 0;
  long insize = 0, outsize = 0, lastsize = 0;
  int oldquality;
  double ratio;
  struct stat file_stat;
  jpeg_saved_marker_ptr cmarker; 
  unsigned char *outbuffer = NULL;
  size_t outbuffersize;
  char *outfname = NULL;
  FILE *infile = NULL, *outfile = NULL;
  int marker_in_count, marker_in_size;
  int compress_err_count = 0;
  int decompress_err_count = 0;
  long average_count = 0;
  double average_rate = 0.0, total_save = 0.0;


  if (rcsid)
  ; /* so compiler won't complain about "unused" rcsid string */

  umask(077);
  signal(SIGINT,own_signal_handler);
  signal(SIGTERM,own_signal_handler);

  /* initialize decompression object */
  dinfo.err = jpeg_std_error(&jderr.pub);
  jpeg_create_decompress(&dinfo);
  jderr.pub.error_exit=my_error_exit;
  jderr.pub.output_message=my_output_message;
  jderr.jump_set = 0;

  /* initialize compression object */
  cinfo.err = jpeg_std_error(&jcerr.pub);
  jpeg_create_compress(&cinfo);
  jcerr.pub.error_exit=my_error_exit;
  jcerr.pub.output_message=my_output_message;
  jcerr.jump_set = 0;


  if (argc<2) {
    if (!quiet_mode) fprintf(stderr,PROGRAMNAME ": file arguments missing\n"
			     "Try '" PROGRAMNAME " --help' for more information.\n");
    exit(1);
  }
 
  /* parse command line parameters */
  while(1) {
    opt_index=0;
    if ((c=getopt_long(argc,argv,"d:hm:nstqvfVpPoT:S:b",long_options,&opt_index))
	      == -1) 
      break;

    switch (c) {
    case 'm':
      {
        int tmpvar;

        if (sscanf(optarg,"%d",&tmpvar) == 1) {
	  quality=tmpvar;
	  if (quality < 0) quality=0;
	  if (quality > 100) quality=100;
	}
	else 
	  fatal("invalid argument for -m, --max");
      }
      break;
    case 'd':
      if (realpath(optarg,dest_path)==NULL || !is_directory(dest_path)) {
	fatal("invalid argument for option -d, --dest");
      }
      strncat(dest_path,DIR_SEPARATOR_S,sizeof(dest_path)-strlen(dest_path)-1);

      if (verbose_mode) 
	fprintf(stderr,"Destination directory: %s\n",dest_path);
      dest=1;
      break;
    case 'v':
      verbose_mode++;
      break;
    case 'h':
      print_usage();
      exit(0);
      break;
    case 'q':
      quiet_mode=1;
      break;
    case 't':
      totals_mode=1;
      break;
    case 'n':
      noaction=1;
      break;
    case 'f':
      force=1;
      break;
    case 'b':
      csv=1;
      quiet_mode=1;
      break;
    case '?':
      break;
    case 'V':
      print_version();
      exit(0);
      break;
    case 'o':
      overwrite_mode=1;
      break;
    case 'p':
      preserve_mode=1;
      break;
    case 'P':
      preserve_perms=1;
      break;
    case 's':
      save_exif=0;
      save_iptc=0;
      save_com=0;
      save_icc=0;
      save_xmp=0;
      break;
    case 'T':
      {
	int tmpvar;
	if (sscanf(optarg,"%d",&tmpvar) == 1) {
	  threshold=tmpvar;
	  if (threshold < 0) threshold=0;
	  if (threshold > 100) threshold=100;
	}
	else fatal("invalid argument for -T, --threshold");
      }
      break;
    case 'S':
      {
	unsigned int tmpvar;
	if (sscanf(optarg,"%u",&tmpvar) == 1) {
	  if (tmpvar > 0 && tmpvar < 100 && optarg[strlen(optarg)-1] == '%' ) {
	    target_size=-tmpvar;
	  } else {
	    target_size=tmpvar;
	  }
	  quality=100;
	}
	else fatal("invalid argument for -S, --size");
      }
      break;

    }
  }


  /* check for '-' option indicating input is from stdin... */
  i=1;
  while (argv[i]) {
    if (argv[i][0]=='-' && argv[i][1]==0) stdin_mode=1;
    i++;
  }

  if (stdin_mode) { stdout_mode=1; force=1; }
  if (stdout_mode) { logs_to_stdout=0; }

  if (all_normal && all_progressive)
    fatal("cannot specify both --all-normal and --all-progressive"); 

  if (verbose_mode) {
    if (quality>=0 && target_size==0) 
      fprintf(stderr,"Image quality limit set to: %d\n",quality);
    if (threshold>=0) 
      fprintf(stderr,"Compression threshold (%%) set to: %d\n",threshold);
    if (all_normal) 
      fprintf(stderr,"All output files will be non-progressive\n");
    if (all_progressive) 
      fprintf(stderr,"All output files will be progressive\n");
    if (target_size > 0) 
      fprintf(stderr,"Target size for output files set to: %u Kbytes.\n",
	      target_size);
    if (target_size < 0) 
      fprintf(stderr,"Target size for output files set to: %u%%\n",
	      -target_size);
  }


  /* loop to process the input files */
  i=1;  
  do {
    if (stdin_mode) {
      infile=stdin;
      set_filemode_binary(infile);
    } else {
      if (!argv[i][0]) continue;
      if (argv[i][0]=='-') continue;
      if (strlen(argv[i]) >= MAXPATHLEN) {
	warn("skipping too long filename: %s",argv[i]);
	continue;
      }

      if (!noaction) {
	/* generate tmp dir & new filename */
	if (dest) {
	  STRNCPY(tmpdir,dest_path,sizeof(tmpdir));
	  STRNCPY(newname,dest_path,sizeof(newname));
	  if (!splitname(argv[i],tmpfilename,sizeof(tmpfilename)))
	    fatal("splitname() failed for: %s",argv[i]);
	  strncat(newname,tmpfilename,sizeof(newname)-strlen(newname)-1);
	} else {
	  if (!splitdir(argv[i],tmpdir,sizeof(tmpdir))) 
	    fatal("splitdir() failed for: %s",argv[i]);
	  STRNCPY(newname,argv[i],sizeof(newname));
	}
      }
      
    retry_point:
      
      if (!is_file(argv[i],&file_stat)) {
	if (is_directory(argv[i])) 
	  warn("skipping directory: %s",argv[i]);
	else
	  warn("skipping special file: %s",argv[i]); 
	continue;
      }
      if ((infile=fopen(argv[i],"rb"))==NULL) {
	warn("cannot open file: %s", argv[i]);
	continue;
      }
    }

   if (setjmp(jderr.setjmp_buffer)) {
     /* error handler for decompress */
     jpeg_abort_decompress(&dinfo);
     fclose(infile);
     if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
     if (!quiet_mode || csv) 
       fprintf(LOG_FH,csv ? ",,,,,error\n" : " [ERROR]\n");
     decompress_err_count++;
     jderr.jump_set=0;
     continue;
   } else {
     jderr.jump_set=1;
   }

   if (!retry && (!quiet_mode || csv)) {
     fprintf(LOG_FH,csv ? "%s," : "%s ",(stdin_mode?"stdin":argv[i])); fflush(LOG_FH); 
   }

   /* prepare to decompress */
   global_error_counter=0;
   jpeg_save_markers(&dinfo, JPEG_COM, 0xffff);
   for (j=0;j<=15;j++) 
     jpeg_save_markers(&dinfo, JPEG_APP0+j, 0xffff);
   jpeg_stdio_src(&dinfo, infile);
   jpeg_read_header(&dinfo, TRUE); 

   /* check for Exif/IPTC/ICC/XMP markers */
   marker_str[0]=0;
   marker_in_count=0;
   marker_in_size=0;
   cmarker=dinfo.marker_list;

   while (cmarker) {
     marker_in_count++;
     marker_in_size+=cmarker->data_length;

     if (cmarker->marker == EXIF_JPEG_MARKER &&
	 !memcmp(cmarker->data,EXIF_IDENT_STRING,EXIF_IDENT_STRING_SIZE))
       strncat(marker_str,"Exif ",sizeof(marker_str)-strlen(marker_str)-1);

     if (cmarker->marker == IPTC_JPEG_MARKER)
       strncat(marker_str,"IPTC ",sizeof(marker_str)-strlen(marker_str)-1);

     if (cmarker->marker == ICC_JPEG_MARKER &&
	 !memcmp(cmarker->data,ICC_IDENT_STRING,ICC_IDENT_STRING_SIZE))
       strncat(marker_str,"ICC ",sizeof(marker_str)-strlen(marker_str)-1);

     if (cmarker->marker == XMP_JPEG_MARKER &&
	 !memcmp(cmarker->data,XMP_IDENT_STRING,XMP_IDENT_STRING_SIZE)) 
       strncat(marker_str,"XMP ",sizeof(marker_str)-strlen(marker_str)-1);

     cmarker=cmarker->next;
   }


   if (verbose_mode > 1) 
     fprintf(LOG_FH,"%d markers found in input file (total size %d bytes)\n",
	     marker_in_count,marker_in_size);
   if (!retry && (!quiet_mode || csv)) {
     fprintf(LOG_FH,csv ? "%dx%d,%dbit,%c," : "%dx%d %dbit %c ",(int)dinfo.image_width,
	     (int)dinfo.image_height,(int)dinfo.num_components*8,
	     (dinfo.progressive_mode?'P':'N'));

     if (!csv) {
       fprintf(LOG_FH,"%s",marker_str);
       if (dinfo.saw_Adobe_marker) fprintf(LOG_FH,"Adobe ");
       if (dinfo.saw_JFIF_marker) fprintf(LOG_FH,"JFIF ");
     }
     fflush(LOG_FH);
   }

   if ((insize=file_size(infile)) < 0)
     fatal("failed to stat() input file");

  /* decompress the file */
   if (quality>=0 && !retry) {
     jpeg_start_decompress(&dinfo);

     /* allocate line buffer to store the decompressed image */
     buf = malloc(sizeof(JSAMPROW)*dinfo.output_height);
     if (!buf) fatal("not enough memory");
     for (j=0;j<dinfo.output_height;j++) {
       buf[j]=malloc(sizeof(JSAMPLE)*dinfo.output_width*
		     dinfo.out_color_components);
       if (!buf[j]) fatal("not enough memory");
     }

     while (dinfo.output_scanline < dinfo.output_height) {
       jpeg_read_scanlines(&dinfo,&buf[dinfo.output_scanline],
			   dinfo.output_height-dinfo.output_scanline);
     }
   } else {
     coef_arrays = jpeg_read_coefficients(&dinfo);
   }

   if (!retry && !quiet_mode) {
     if (global_error_counter==0) fprintf(LOG_FH," [OK] ");
     else fprintf(LOG_FH," [WARNING] ");
     fflush(LOG_FH);
   }

     

   if (dest && !noaction) {
     if (file_exists(newname) && !overwrite_mode) {
       warn("target file already exists: %s\n",newname);
       jpeg_abort_decompress(&dinfo);
       fclose(infile);
       if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
       continue;
     }
   }


   if (setjmp(jcerr.setjmp_buffer)) {
     /* error handler for compress failures */
     
     jpeg_abort_compress(&cinfo);
     jpeg_abort_decompress(&dinfo);
     fclose(infile);
     if (!quiet_mode) fprintf(LOG_FH," [Compress ERROR]\n");
     if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
     compress_err_count++;
     jcerr.jump_set=0;
     continue;
   } else {
     jcerr.jump_set=1;
   }


   lastsize = 0;
   searchcount = 0;
   searchdone = 0;
   oldquality = 200;



  binary_search_loop:

   /* allocate memory buffer that should be large enough to store the output JPEG... */
   if (outbuffer) free(outbuffer);
   outbuffersize=insize + 32768;
   outbuffer=malloc(outbuffersize);
   if (!outbuffer) fatal("not enough memory");

   /* setup custom "destination manager" for libjpeg to write to our buffer */
   jpeg_memory_dest(&cinfo, &outbuffer, &outbuffersize, 65536);

   if (quality>=0 && !retry) {
     /* lossy "optimization" ... */

     cinfo.in_color_space=dinfo.out_color_space;
     cinfo.input_components=dinfo.output_components;
     cinfo.image_width=dinfo.image_width;
     cinfo.image_height=dinfo.image_height;
     jpeg_set_defaults(&cinfo); 
     jpeg_set_quality(&cinfo,quality,TRUE);
     if ( (dinfo.progressive_mode || all_progressive) && !all_normal )
       jpeg_simple_progression(&cinfo);
     cinfo.optimize_coding = TRUE;

     j=0;
     jpeg_start_compress(&cinfo,TRUE);
     
     /* write markers */
     write_markers(&dinfo,&cinfo);

     /* write image */
     while (cinfo.next_scanline < cinfo.image_height) {
       jpeg_write_scanlines(&cinfo,&buf[cinfo.next_scanline],
			    dinfo.output_height);
     }

   } else {
     /* lossless "optimization" ... */

     jpeg_copy_critical_parameters(&dinfo, &cinfo);
     if ( (dinfo.progressive_mode || all_progressive) && !all_normal )
       jpeg_simple_progression(&cinfo);
     cinfo.optimize_coding = TRUE;

     /* write image */
     jpeg_write_coefficients(&cinfo, coef_arrays);

     /* write markers */
     write_markers(&dinfo,&cinfo);

   }

   jpeg_finish_compress(&cinfo);
   outsize=outbuffersize;

   if (target_size != 0 && !retry) {
     /* perform (binary) search to try to reach target file size... */

     long osize = outsize/1024;
     long isize = insize/1024;
     long tsize = target_size;

     if (tsize < 0) { 
       tsize=((-target_size)*insize/100)/1024; 
       if (tsize < 1) tsize=1;
     }

     if (osize == tsize || searchdone || searchcount >= 8 || tsize > isize) {
       if (searchdone < 42 && lastsize > 0) {
	 if (abs(osize-tsize) > abs(lastsize-tsize)) {
	   if (verbose_mode) fprintf(LOG_FH,"(revert to %d)",oldquality);
	   searchdone=42;
	   quality=oldquality;
	   goto binary_search_loop;
	 }
       }
       if (verbose_mode) fprintf(LOG_FH," ");
       
     } else {
       int newquality;
       int dif = floor((abs(oldquality-quality)/2.0)+0.5);
       if (osize > tsize) {
	 newquality=quality-dif;
	 if (dif < 1) { newquality--; searchdone=1; }
	 if (newquality < 0) { newquality=0; searchdone=2; }
       } else {
	 newquality=quality+dif;
	 if (dif < 1) { newquality++; searchdone=3; }
	 if (newquality > 100) { newquality=100; searchdone=4; }
       }
       oldquality=quality;
       quality=newquality;

       if (verbose_mode) fprintf(LOG_FH,"(try %d)",quality);

       lastsize=osize;
       searchcount++;
       goto binary_search_loop;
     }
   } 

   if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
   jpeg_finish_decompress(&dinfo);
   fclose(infile);


   if (quality>=0 && outsize>=insize && !retry && !stdin_mode) {
     if (verbose_mode) fprintf(LOG_FH,"(retry w/lossless) ");
     retry=1;
     goto retry_point; 
   }

   retry=0;
   ratio=(insize-outsize)*100.0/insize;
   if (!quiet_mode || csv)
     fprintf(LOG_FH,csv ? "%ld,%ld,%0.2f," : "%ld --> %ld bytes (%0.2f%%), ",insize,outsize,ratio);
   average_count++;
   average_rate+=(ratio<0 ? 0.0 : ratio);

   if ((outsize < insize && ratio >= threshold) || force) {
        total_save+=(insize-outsize)/1024.0;
	if (!quiet_mode || csv) fprintf(LOG_FH,csv ? "optimized\n" : "optimized.\n");
        if (noaction) continue;

	if (stdout_mode) {
	  outfname=NULL;
	  set_filemode_binary(stdout);
	  if (fwrite(outbuffer,outbuffersize,1,stdout) != 1)
	    fatal("write failed to stdout");
	} else {
	  if (preserve_perms && !dest) {
	    /* make backup of the original file */
	    snprintf(tmpfilename,sizeof(tmpfilename),"%s.jpegoptim.bak",newname);
	    if (verbose_mode > 1 && !quiet_mode) 
	      fprintf(LOG_FH,"creating backup of original image as: %s\n",tmpfilename);
	    if (file_exists(tmpfilename))
	      fatal("backup file already exists: %s",tmpfilename);
	    if (copy_file(newname,tmpfilename))
	      fatal("failed to create backup of original file");
	    if ((outfile=fopen(newname,"wb"))==NULL)
	      fatal("error opening output file: %s", newname);
	    outfname=newname;
	  } else {
#ifdef HAVE_MKSTEMPS
	    /* rely on mkstemps() to create us temporary file safely... */  
	    snprintf(tmpfilename,sizeof(tmpfilename),
		     "%sjpegoptim-%d-%d.XXXXXX.tmp", tmpdir, (int)getuid(), (int)getpid());
	    if ((tmpfd = mkstemps(tmpfilename,4)) < 0) 
	      fatal("error creating temp file: mkstemps() failed");
	    if ((outfile=fdopen(tmpfd,"wb"))==NULL) 
#else
	      /* if platform is missing mkstemps(), try to create at least somewhat "safe" temp file... */  
	      snprintf(tmpfilename,sizeof(tmpfilename),
		       "%sjpegoptim-%d-%d.%d.tmp", tmpdir, (int)getuid(), (int)getpid(),time(NULL));
	    tmpfd=0;
	    if ((outfile=fopen(tmpfilename,"wb"))==NULL) 
#endif
	      fatal("error opening temporary file: %s",tmpfilename);
	    outfname=tmpfilename;
	  }

	  if (verbose_mode > 1 && !quiet_mode) 
	    fprintf(LOG_FH,"writing %lu bytes to file: %s\n",
		    (long unsigned int)outbuffersize, outfname);
	  if (fwrite(outbuffer,outbuffersize,1,outfile) != 1)
	    fatal("write failed to file: %s", outfname);
	  fclose(outfile);
	}

	if (outfname) {
	  
	  if (preserve_mode) {
	    /* preserve file modification time */
	    struct utimbuf time_save;
	    time_save.actime=file_stat.st_atime;
	    time_save.modtime=file_stat.st_mtime;
	    if (utime(outfname,&time_save) != 0) 
	      warn("failed to reset output file time/date");
	  }

	  if (preserve_perms && !dest) {
	    /* original file was already replaced, remove backup... */
	    if (delete_file(tmpfilename))
	      warn("failed to remove backup file: %s",tmpfilename);
	  } else {
	    /* make temp file to be the original file... */

	    /* preserve file mode */
	    if (chmod(outfname,(file_stat.st_mode & 0777)) != 0) 
	      warn("failed to set output file mode"); 

	    /* preserve file group (and owner if run by root) */
	    if (chown(outfname,
		      (geteuid()==0 ? file_stat.st_uid : -1),
		      file_stat.st_gid) != 0)
	      warn("failed to reset output file group/owner");

	    if (verbose_mode > 1 && !quiet_mode) 
	      fprintf(LOG_FH,"renaming: %s to %s\n",outfname,newname);
	    if (rename_file(outfname,newname)) fatal("cannot rename temp file");
	  }
	}
   } else {
     if (!quiet_mode || csv) fprintf(LOG_FH,csv ? "skipped\n" : "skipped.\n");
   }
   

  } while (++i<argc && !stdin_mode);


  if (totals_mode && !quiet_mode)
    fprintf(LOG_FH,"Average ""compression"" (%ld files): %0.2f%% (%0.0fk)\n",
	    average_count, average_rate/average_count, total_save);
  jpeg_destroy_decompress(&dinfo);
  jpeg_destroy_compress(&cinfo);

  return (decompress_err_count > 0 || compress_err_count > 0 ? 1 : 0);;
}
Esempio n. 6
0
static HRESULT WINAPI EnumWorkItems_Next(IEnumWorkItems *iface, ULONG count, LPWSTR **names, ULONG *fetched)
{
    static const WCHAR tasksW[] = { '\\','T','a','s','k','s','\\','*',0 };
    EnumWorkItemsImpl *This = impl_from_IEnumWorkItems(iface);
    WCHAR path[MAX_PATH];
    WIN32_FIND_DATAW data;
    ULONG enumerated, allocated, dummy;
    LPWSTR *list;
    HRESULT hr = S_FALSE;

    TRACE("(%p)->(%u %p %p)\n", This, count, names, fetched);

    if (!count || !names || (!fetched && count > 1)) return E_INVALIDARG;

    if (!fetched) fetched = &dummy;

    *names = NULL;
    *fetched = 0;
    enumerated = 0;
    list = NULL;

    if (This->handle == INVALID_HANDLE_VALUE)
    {
        GetWindowsDirectoryW(path, MAX_PATH);
        lstrcatW(path, tasksW);
        This->handle = FindFirstFileW(path, &data);
        if (This->handle == INVALID_HANDLE_VALUE)
            return S_FALSE;
    }
    else
    {
        if (!FindNextFileW(This->handle, &data))
            return S_FALSE;
    }

    allocated = 64;
    list = CoTaskMemAlloc(allocated * sizeof(list[0]));
    if (!list) return E_OUTOFMEMORY;

    do
    {
        if (is_file(&data))
        {
            if (enumerated >= allocated)
            {
                LPWSTR *new_list;
                allocated *= 2;
                new_list = CoTaskMemRealloc(list, allocated * sizeof(list[0]));
                if (!new_list)
                {
                    hr = E_OUTOFMEMORY;
                    break;
                }
                list = new_list;
            }

            list[enumerated] = CoTaskMemAlloc((lstrlenW(data.cFileName) + 1) * sizeof(WCHAR));
            if (!list[enumerated])
            {
                hr = E_OUTOFMEMORY;
                break;
            }

            lstrcpyW(list[enumerated], data.cFileName);
            enumerated++;

            if (enumerated >= count)
            {
                hr = S_OK;
                break;
            }
        }
    } while (FindNextFileW(This->handle, &data));

    if (FAILED(hr))
        free_list(list, enumerated);
    else
    {
        *fetched = enumerated;
        *names = list;
    }

    return hr;
}
Esempio n. 7
0
bool is_file (const std::string& name)
{
    return is_file (name.c_str ());
}
Esempio n. 8
0
/** int rk_check_file(char *value, char *pattern)
 */
int rk_check_file(char *file, char *pattern)
{
    char *split_file;
    int full_negate = 0; 
    int pt_result = 0; 
    
    FILE *fp;
    char buf[OS_SIZE_2048 +1];
    
    
    /* If string is null, we don't match */
    if(file == NULL)
    {
        return(0);
    }


    /* Checking if the file is divided */
    split_file = strchr(file, ',');
    if(split_file)
    {
        *split_file = '\0';
        split_file++;
    }


    /* Getting each file */
    do
    {
        

        /* If we don't have a pattern, just check if the file/dir is there */
        if(pattern == NULL)
        {
            if(is_file(file))
            {
                int i = 0;
                char _b_msg[OS_SIZE_1024 +1];

                _b_msg[OS_SIZE_1024] = '\0';
                snprintf(_b_msg, OS_SIZE_1024, " File: %s.",
                         file);

                /* Already present. */
                if(_is_str_in_array(rootcheck.alert_msg, _b_msg))
                {
                    return(1);
                }

                while(rootcheck.alert_msg[i] && (i < 255))
                    i++;
                
                if(!rootcheck.alert_msg[i])
                    os_strdup(_b_msg, rootcheck.alert_msg[i]);

                return(1);
            }
        }

        else
        {
            full_negate = pt_check_negate(pattern); 
            /* Checking for a content in the file */
            debug1("checking file: %s", file); 
            fp = fopen(file, "r");
            if(fp)
            {

                debug1(" starting new file: %s", file); 
                buf[OS_SIZE_2048] = '\0';
                while(fgets(buf, OS_SIZE_2048, fp) != NULL)
                {
                    char *nbuf;

                    /* Removing end of line */
                    nbuf = strchr(buf, '\n');
                    if(nbuf)
                    {
                        *nbuf = '\0';
                    }


                    #ifdef WIN32
                    /* Removing end of line */
                    nbuf = strchr(buf, '\r');
                    if(nbuf)
                    {
                        *nbuf = '\0';
                    }
                    #endif


                    /* Matched */
                    pt_result = pt_matches(buf, pattern);
                    debug1("Buf == \"%s\"", buf); 
                    debug1("Pattern == \"%s\"", pattern);
                    debug1("pt_result == %d and full_negate == %d", pt_result, full_negate);
                    if((pt_result == 1 && full_negate == 0) )
                    {
                        debug1("alerting file %s on line %s", file, buf);
                        int i = 0;
                        char _b_msg[OS_SIZE_1024 +1];


                        /* Closing the file before dealing with the alert. */
                        fclose(fp);

                        /* Generating the alert itself. */
                        _b_msg[OS_SIZE_1024] = '\0';
                        snprintf(_b_msg, OS_SIZE_1024, " File: %s.",
                                 file);
                        
                        /* Already present. */
                        if(_is_str_in_array(rootcheck.alert_msg, _b_msg))
                        {
                            return(1);
                        }

                        while(rootcheck.alert_msg[i] && (i < 255))
                            i++;

                        if(!rootcheck.alert_msg[i])
                        os_strdup(_b_msg, rootcheck.alert_msg[i]);

                        return(1);
                    }
                    else if((pt_result == 0 && full_negate == 1) )
                    {
                        /* found a full+negate match so no longer need to search
                         * break out of loop and amke sure the full negate does 
                         * not alertin 
                         */
                        debug1("found a complete match for full_negate");
                        full_negate = 0; 
                        break; 
                    }
                }

                fclose(fp);

                if(full_negate == 1) 
                {
                    debug1("full_negate alerting - file %s",file);
                    int i = 0;
                    char _b_msg[OS_SIZE_1024 +1];

                    /* Generating the alert itself. */
                    _b_msg[OS_SIZE_1024] = '\0';
                    snprintf(_b_msg, OS_SIZE_1024, " File: %s.",
                             file);
                    
                    /* Already present. */
                    if(_is_str_in_array(rootcheck.alert_msg, _b_msg))
                    {
                        return(1);
                    }

                    while(rootcheck.alert_msg[i] && (i < 255))
                        i++;

                    if(!rootcheck.alert_msg[i])
                    os_strdup(_b_msg, rootcheck.alert_msg[i]);

                    return(1);
                }
            }
        }

        if(split_file)
        {
            file = split_file;
            split_file = strchr(split_file, ',');
            if(split_file)
            {
                split_file++;
            }
        }
        
        
    }while(split_file);


    return(0);
}
Esempio n. 9
0
int cert_verify_file(
    CERT_SIGS* signatures, const char* origFile, const char* trustLocation
) {
    MD5_CTX md5CTX;
    int rbytes;
    unsigned char md5_md[MD5_DIGEST_LENGTH],  rbuf[2048];
    char buf[256];
    char fbuf[MAXPATHLEN];
    int verified = false;
    int file_counter = 0;
    DATA_BLOCK sig_db;
    BIO *bio;
    X509 *cert;
    X509_NAME *subj;

    if (signatures->signatures.size() == 0) {
        printf("No signatures available for file ('%s').\n", origFile);
        fflush(stdout);
        return false;
    }
    SSL_library_init();
    if (!is_file(origFile)) return false;
    FILE* of = boinc_fopen(origFile, "r");
    if (!of) return false;
    MD5_Init(&md5CTX);
    while (0 != (rbytes = (int)fread(rbuf, 1, sizeof(rbuf), of))) {
	    MD5_Update(&md5CTX, rbuf, rbytes);
    }
    MD5_Final(md5_md, &md5CTX);
    fclose(of);
    for(unsigned int i=0;i < signatures->signatures.size(); i++) {
        sig_db.data = (unsigned char*)calloc(128, sizeof(char));
        if (sig_db.data == NULL) {
            printf("Cannot allocate 128 bytes for signature buffer\n");
            return false;
        }
        sig_db.len=128;
        sscan_hex_data(signatures->signatures.at(i).signature, sig_db);
        file_counter = 0;
        while (1) {
            snprintf(fbuf, MAXPATHLEN, "%s/%s.%d", trustLocation, signatures->signatures.at(i).hash,
                file_counter);
#ifndef _USING_FCGI_
            FILE *f = fopen(fbuf, "r");
#else
            FCGI_FILE *f = FCGI::fopen(fbuf, "r");
#endif 
            if (f==NULL)
                break;
            fclose(f);
            bio = BIO_new(BIO_s_file());
            BIO_read_filename(bio, fbuf);
            if (NULL == (cert = PEM_read_bio_X509(bio, NULL, 0, NULL))) {
        	    BIO_vfree(bio);
                printf("Cannot read certificate ('%s')\n", fbuf);
                file_counter++;
        	    continue;
            }
            fflush(stdout);
            subj = X509_get_subject_name(cert);
            X509_NAME_oneline(subj, buf, 256);
            // ???
            //X509_NAME_free(subj);
            X509_free(cert);
    	    BIO_vfree(bio);
            if (strcmp(buf, signatures->signatures.at(i).subject)) {
                printf("Subject does not match ('%s' <-> '%s')\n", buf, signatures->signatures.at(i).subject);
                file_counter++;
                continue;
            } 
            verified = check_validity_of_cert(fbuf, md5_md, sig_db.data, 128, trustLocation);
            if (verified) 
                break;
            file_counter++;
        }
        free(sig_db.data);
        if (!verified)
            return false;
    }
    return verified;
}
void mexFunction ( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
	Dbptr	db;
	Point	*polygon;
	char 	*pname;
	char	*ptype;
	char	*auth;
	char	*dir;
	char	*dfile;
	char	*s_pcode;
	int		pcode;
	double	*lat;
	double	*lon;
	long		nsamp;
	mwSize 	nlat,nlon;
	const mwSize		*dimensions;
	int	i;
	int retcode;
	char *dbfile_name;
	char *dbschema_name;
	char errmsg[STRSZ];


	if ( nrhs != 9 ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	} else if ( ! get_dbptr( prhs[0], &db ) ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	} else if ( !mxIsDouble( prhs[1] ) ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	} else if ( !mxIsDouble( prhs[2] ) ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	} else if ( !mxIsChar( prhs[3] ) ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	} else if ( !mxIsChar( prhs[4] ) ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	} else if ( !mxIsChar( prhs[5] ) ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	} else if ( !mxIsChar( prhs[6] ) ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	} else if ( !mxIsChar( prhs[7] ) ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	} else if ( !mxIsChar( prhs[8] ) ) {
		antelope_mexUsageMsgTxt ( USAGE ); return;
	}
	dimensions= (mwSize*) mxGetDimensions( prhs[1] );
	if (dimensions[1] != 1 && dimensions[0] != 1) {
		mexErrMsgTxt("writepolygondata: LAT must have dimensions Nx1 or 1xN\n");
	}
	if (dimensions[1] == 1) {
		nlat= dimensions[0];
	} else {
		nlat= dimensions[1];
	}
	dimensions= (mwSize *)mxGetDimensions( prhs[2] );
	if (dimensions[1] != 1 && dimensions[0] != 1) {
		mexErrMsgTxt("writepolygondata: LON must have dimensions Nx1 or 1xN\n");
	}
	if (dimensions[1] == 1) {
		nlon= dimensions[0];
	} else {
		nlon= dimensions[1];
	}
	if (nlat != nlon) {
		mexErrMsgTxt("writepolygondata: LAT and LON must be of same size\n");
	}
	if( ( retcode = dbquery(db, dbDATABASE_FILENAME, &dbfile_name) ) < 0 ) {
			mexErrMsgTxt("writepolygondata: problem getting descriptor filename\n");
	}
	if ( is_file(dbfile_name)==1 ) {
		if( ( retcode = dbquery(db, dbSCHEMA_NAME, &dbschema_name) ) < 0 ) {
				mexErrMsgTxt("writepolygondata: problem getting schema name\n");
		} else {
				if (strmatches(dbschema_name,"polygon1.2.*", 0) != 1) {
						sprintf(errmsg, "writepolygondata: wrong schema '%s' for output database '%s'\n",dbschema_name,dbfile_name);
						mexErrMsgTxt(errmsg);
				}
		}
	} else {
		sprintf(errmsg, "writepolygondata: please create database schema '%s' with schema polygon1.2\n",dbfile_name);
		mexErrMsgTxt(errmsg);
			//there might be a fix, but for the moment this simply does NOT work
		if (dbcreate(dbfile_name,"polygon1.2",0, 0, 0) != 0 ) {
				mexErrMsgTxt("writepolygondata: problem with dbcreate\n");
		}
	}


	
	nsamp= (long) nlat;

	lat= mxGetPr(prhs[1]);
	lon= mxGetPr(prhs[2]);
	polygon= mxCalloc(nsamp+1,sizeof(Point));
	
	for (i= 0; i < nsamp; i++) {
		polygon[i].lat=lat[i];
		polygon[i].lon=lon[i];
	}

	get_malloced_string(prhs[3],&pname);
	get_malloced_string(prhs[4],&ptype);
	get_malloced_string(prhs[5],&auth);
	get_malloced_string(prhs[6],&dir);
	get_malloced_string(prhs[7],&dfile);
	get_malloced_string(prhs[8],&s_pcode);

	pcode= polycode(s_pcode);

	/*maybe nsamp -1, check later...*/
	writePolygonData(db,polygon,nsamp,pname,1,1,ptype,auth,dir,dfile,pcode);

	antelope_mex_clear_register(1);

	mxFree(polygon);
	mxFree(s_pcode);
	mxFree(dfile);
	mxFree(dir);
	mxFree(auth);
	mxFree(ptype);
	mxFree(pname);
}
Esempio n. 11
0
int main(int argc, char **argv) {
    char *image;

    // Before we do anything, check privileges and drop permission
    singularity_priv_init();
    singularity_priv_drop();

#ifdef SINGULARITY_SUID
    singularity_message(VERBOSE2, "Running SUID program workflow\n");

    singularity_message(VERBOSE2, "Checking program has appropriate permissions\n");
    if ( ( getuid() != 0 ) && ( ( is_owner("/proc/self/exe", 0) < 0 ) || ( is_suid("/proc/self/exe") < 0 ) ) ) {
        singularity_abort(255, "This program must be SUID root\n");
    }

    singularity_message(VERBOSE2, "Checking configuration file is properly owned by root\n");
    if ( is_owner(joinpath(SYSCONFDIR, "/singularity/singularity.conf"), 0 ) < 0 ) {
        singularity_abort(255, "Running in privileged mode, root must own the Singularity configuration file\n");
    }

    singularity_config_init(joinpath(SYSCONFDIR, "/singularity/singularity.conf"));

    singularity_message(VERBOSE2, "Checking that we are allowed to run as SUID\n");
    if ( singularity_config_get_bool(ALLOW_SETUID) == 0 ) {
        singularity_abort(255, "SUID mode has been disabled by the sysadmin... Aborting\n");
    }

    singularity_message(VERBOSE2, "Checking if we were requested to run as NOSUID by user\n");
    if ( envar_defined("SINGULARITY_NOSUID") == TRUE ) {
        singularity_abort(1, "NOSUID mode has been requested... Aborting\n");
    }

#else
    singularity_message(VERBOSE, "Running NON-SUID program workflow\n");

    singularity_message(DEBUG, "Checking program has appropriate permissions\n");
    if ( is_suid("/proc/self/exe") >= 0 ) {
        singularity_abort(255, "This program must **NOT** be SUID\n");
    }

    singularity_config_init(joinpath(SYSCONFDIR, "/singularity/singularity.conf"));

    if ( singularity_priv_getuid() != 0 ) {
        singularity_message(VERBOSE2, "Checking that we are allowed to run as SUID\n");
        if ( singularity_config_get_bool(ALLOW_SETUID) == 1 ) {
            singularity_message(VERBOSE2, "Checking if we were requested to run as NOSUID by user\n");
            if ( envar_defined("SINGULARITY_NOSUID") == FALSE ) {
                char sexec_suid_path[] = LIBEXECDIR "/singularity/sexec-suid";
		
		singularity_message(VERBOSE, "Checking for sexec-suid at %s\n", sexec_suid_path);

		if ( is_file(sexec_suid_path) == 0 ) {
                    if ( ( is_owner(sexec_suid_path, 0 ) == 0 ) && ( is_suid(sexec_suid_path) == 0 ) ) {
                        singularity_message(VERBOSE, "Invoking SUID sexec: %s\n", sexec_suid_path);

                        execv(sexec_suid_path, argv); // Flawfinder: ignore
                        singularity_abort(255, "Failed to execute sexec binary (%s): %s\n", sexec_suid_path, strerror(errno));
                    } else {
                        singularity_message(VERBOSE, "Not invoking SUID mode: SUID sexec permissions not properly set\n");
                    }
		}
		else {
		    singularity_message(VERBOSE, "Not invoking SUID mode: SUID sexec not installed\n");
		}
            } else {
                singularity_message(VERBOSE, "Not invoking SUID mode: NOSUID mode requested\n");
            }
        } else {
            singularity_message(VERBOSE, "Not invoking SUID mode: disallowed by the system administrator\n");
        }
    } else {
        singularity_message(VERBOSE, "Not invoking SUID mode: running as root\n");
    }

#endif /* SINGULARITY_SUID */

    if ( ( image = envar_path("SINGULARITY_IMAGE") ) == NULL ) {
        singularity_abort(255, "SINGULARITY_IMAGE not defined!\n");
    }

    singularity_action_init();
    singularity_rootfs_init(image);
    singularity_sessiondir_init(image);

    free(image);

    singularity_ns_unshare();

    singularity_rootfs_mount();

    singularity_rootfs_check();

    singularity_file();

    singularity_mount();

    singularity_rootfs_chroot();

    singularity_action_do(argc, argv);

    return(0);

}
Esempio n. 12
0
void init(int argc, char **argv){
	if(argc < 2){
		usage(argc, argv);
		exit(0);
	}
	signal(SIGPIPE, SIG_IGN);

	{
		struct timeval tv;
		if(gettimeofday(&tv, NULL) == -1){
			srand(time(NULL) + getpid());
		}else{
			srand(tv.tv_sec + tv.tv_usec + getpid());
		}
	}

	bool is_daemon = false;
	const char *conf_file = NULL;
	for(int i=1; i<argc; i++){
		if(strcmp(argv[i], "-d") == 0){
			is_daemon = true;
		}else{
			conf_file = argv[i];
		}
	}

	if(conf_file == NULL){
		usage(argc, argv);
		exit(0);
	}

	if(!is_file(conf_file)){
		fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
		exit(0);
	}

	conf = Config::load(conf_file);
	if(!conf){
		fprintf(stderr, "error loading conf file: '%s'\n", conf_file);
		exit(0);
	}
	{
		std::string conf_dir = real_dirname(conf_file);
		if(chdir(conf_dir.c_str()) == -1){
			fprintf(stderr, "error chdir: %s\n", conf_dir.c_str());
			exit(0);
		}
	}


	std::string log_output;
	int log_rotate_size = 0;
	{ // logger
		int log_level = Logger::get_level(conf->get_str("logger.level"));
		log_rotate_size = conf->get_num("logger.rotate.size");
		if(log_rotate_size < 1024 * 1024){
			log_rotate_size = 1024 * 1024;
		}
		log_output = conf->get_str("logger.output");
		if(log_output == ""){
			log_output = "stdout";
		}
		if(log_open(log_output.c_str(), log_level, true, log_rotate_size) == -1){
			fprintf(stderr, "error open log file: %s\n", log_output.c_str());
			exit(0);
		}
	}

	check_pidfile();
	if(is_daemon){
		daemonize();
	}

	log_info("starting icomet %s...", ICOMET_VERSION);
	log_info("config file: %s", conf_file);
	log_info("log_level       : %s", conf->get_str("logger.level"));
	log_info("log_output      : %s", log_output.c_str());
	log_info("log_rotate_size : %d", log_rotate_size);


	evbase = event_base_new();
	if(!evbase){
		fprintf(stderr, "create evbase error!\n");
		exit(0);
	}
	admin_http = evhttp_new(evbase);
	if(!admin_http){
		fprintf(stderr, "create admin_http error!\n");
		exit(0);
	}
	front_http = evhttp_new(evbase);
	if(!front_http){
		fprintf(stderr, "create front_http error!\n");
		exit(0);
	}
	
	sigint_event = evsignal_new(evbase, SIGINT, signal_cb, NULL);
	if(!sigint_event || event_add(sigint_event, NULL)<0){
		fprintf(stderr, "Could not create/add a signal event!\n");
		exit(0);
	}
	sigterm_event = evsignal_new(evbase, SIGTERM, signal_cb, NULL);
	if(!sigterm_event || event_add(sigterm_event, NULL)<0){
		fprintf(stderr, "Could not create/add a signal event!\n");
		exit(0);
	}
	timer_event = event_new(evbase, -1, EV_PERSIST, timer_cb, NULL);
	{
		struct timeval tv;
		tv.tv_sec = CHANNEL_CHECK_INTERVAL;
		tv.tv_usec = 0;
		if(!timer_event || evtimer_add(timer_event, &tv)<0){
			fprintf(stderr, "Could not create/add a timer event!\n");
			exit(0);
		}
	}
}
    TEST_FIXTURE(file_directory_test_base, directory_list_files_and_directories)
    {
        m_directory.create_if_not_exists(azure::storage::file_access_condition(), azure::storage::file_request_options(), m_context);

        azure::storage::list_file_and_diretory_result_iterator end_of_list;
        for (auto iter = m_share.get_root_directory_reference().list_files_and_directories(); iter != end_of_list; ++iter)
        {
            CHECK_EQUAL(iter->is_directory(), true);
            CHECK_EQUAL(iter->is_file(), false);
            auto directory = iter->as_directory();

            check_equal(directory, m_directory);

            CHECK(directory.get_parent_share_reference().is_valid());
            check_equal(m_share, directory.get_parent_share_reference());

            CHECK(!directory.uri().primary_uri().is_empty());
            CHECK(directory.metadata().empty());
            CHECK(directory.properties().etag().empty());

            CHECK(!directory.properties().last_modified().is_initialized());
        }

        // more complicated file structure.
        const size_t size = 2;
        std::vector<utility::string_t> directories;
        std::vector<utility::string_t> files;
        for (size_t i = 0; i < size; ++i)
        {
            directories.push_back(_XPLATSTR("directory") + get_random_string(10));
        }
        for (size_t i = 0; i < size; ++i)
        {
            files.push_back(_XPLATSTR("file") + get_random_string(10));
        }
        for (size_t i = 0; i < size; ++i)
        {
            auto directory = m_share.get_directory_reference(directories[i]);
            directory.create_if_not_exists(azure::storage::file_access_condition(), azure::storage::file_request_options(), m_context);

            for (size_t j = 0; j < size; ++j)
            {
                auto subdirectory = directory.get_subdirectory_reference(directories[j]);
                subdirectory.create_if_not_exists(azure::storage::file_access_condition(), azure::storage::file_request_options(), m_context);
                for (size_t k = 0; k < size; ++k)
                {
                    auto file = subdirectory.get_file_reference(files[k]);
                    file.create_if_not_exists(512U, azure::storage::file_access_condition(), azure::storage::file_request_options(), m_context);
                }
            }
            for (size_t j = 0; j < size; ++j)
            {
                auto file = directory.get_file_reference(files[j]);
                file.create_if_not_exists(512U, azure::storage::file_access_condition(), azure::storage::file_request_options(), m_context);
            }
            auto file = m_share.get_root_directory_reference().get_file_reference(files[i]);
            file.create_if_not_exists(512U, azure::storage::file_access_condition(), azure::storage::file_request_options(), m_context);
        }

        auto direcotries_one = directories;
        auto files_one = files;
        for (auto iter = m_share.get_root_directory_reference().list_files_and_directories(); iter != end_of_list; ++iter)
        {
            if (iter->is_directory())
            {
                auto directory2 = iter->as_directory();
                CHECK(directory2.get_parent_share_reference().is_valid());
                check_equal(m_share, directory2.get_parent_share_reference());
                CHECK(!directory2.uri().primary_uri().is_empty());
                CHECK(directory2.metadata().empty());
                CHECK(directory2.properties().etag().empty());
                CHECK(!directory2.properties().last_modified().is_initialized());

                auto found = false;
                for (auto directory_name = direcotries_one.begin(); directory_name != direcotries_one.end(); directory_name++)
                {
                    if (*directory_name == directory2.name())
                    {
                        direcotries_one.erase(directory_name);
                        found = true;
                        break;
                    }
                }

                auto direcotries_two = directories;
                auto files_two = files;
                for (auto iter2 = directory2.list_files_and_directories(); found && iter2 != end_of_list; ++iter2)
                {
                    if (iter2->is_directory())
                    {
                        auto directory3 = iter2->as_directory();
                        CHECK(directory3.get_parent_share_reference().is_valid());
                        check_equal(m_share, directory3.get_parent_share_reference());
                        CHECK(!directory3.uri().primary_uri().is_empty());
                        CHECK(directory3.metadata().empty());
                        CHECK(directory3.properties().etag().empty());
                        CHECK(!directory3.properties().last_modified().is_initialized());

                        for (auto directory_name = direcotries_two.begin(); directory_name != direcotries_two.end(); directory_name++)
                        {
                            if (*directory_name == directory3.name())
                            {
                                direcotries_two.erase(directory_name);
                                break;
                            }
                        }

                        auto files_three = files;
                        for (auto iter3 = directory3.list_files_and_directories(); iter3 != end_of_list; ++iter3)
                        {
                            CHECK(iter3->is_file());
                            auto file = iter3->as_file();
                            CHECK(file.get_parent_share_reference().is_valid());
                            check_equal(m_share, file.get_parent_share_reference());
                            CHECK(!file.uri().primary_uri().is_empty());
                            CHECK(file.metadata().empty());
                            CHECK(file.properties().etag().empty());
                            CHECK(!file.properties().last_modified().is_initialized());

                            for (auto file_name = files_three.begin(); file_name != files_three.end(); file_name++)
                            {
                                if (*file_name == file.name())
                                {
                                    files_three.erase(file_name);
                                    break;
                                }
                            }
                        }
                        CHECK(files_three.empty());
                    }
                    else if (iter2->is_file())
                    {
                        auto file = iter2->as_file();
                        CHECK(file.get_parent_share_reference().is_valid());
                        check_equal(m_share, file.get_parent_share_reference());
                        CHECK(!file.uri().primary_uri().is_empty());
                        CHECK(file.metadata().empty());
                        CHECK(file.properties().etag().empty());
                        CHECK(!file.properties().last_modified().is_initialized());

                        for (auto file_name = files_two.begin(); file_name != files_two.end(); file_name++)
                        {
                            if (*file_name == file.name())
                            {
                                files_two.erase(file_name);
                                break;
                            }
                        }
                    }

                }
                CHECK(!found || direcotries_two.empty());
                CHECK(!found || files_two.empty());
            }
            else if (iter->is_file())
            {
                auto file = iter->as_file();
                CHECK(file.get_parent_share_reference().is_valid());
                check_equal(m_share, file.get_parent_share_reference());
                CHECK(!file.uri().primary_uri().is_empty());
                CHECK(file.metadata().empty());
                CHECK(file.properties().etag().empty());
                CHECK(!file.properties().last_modified().is_initialized());

                for (auto file_name = files_one.begin(); file_name != files_one.end(); file_name++)
                {
                    if (*file_name == file.name())
                    {
                        files_one.erase(file_name);
                        break;
                    }
                }
            }
        }

        CHECK(direcotries_one.empty());
        CHECK(files_one.empty());
    }
Esempio n. 14
0
void FilesystemTest::testDirectory() {
#ifdef _WIN32
	const string test_subdir = test_dir->Path() + "\\a";
	const string test_subsubdir = test_subdir + "\\b";
	const string test_file = test_subsubdir + "\\c.txt";
#else
	const string test_subdir = test_dir->Path() + "/a";
	const string test_subsubdir = test_subdir + "/b";
	const string test_file = test_subsubdir + "/c";
#endif

	CPPUNIT_ASSERT_MESSAGE(
		"inexistant directory is a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"inexistant directory is a directory",
		!is_dir(test_subdir));

	CPPUNIT_ASSERT_MESSAGE(
		"failed to create test subdir",
		make_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is not a directory",
		is_dir(test_subdir));

	CPPUNIT_ASSERT_MESSAGE(
		"failed to remove test subdir",
		remove_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory became a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory is still a directory",
		!is_dir(test_subdir));

	CPPUNIT_ASSERT_MESSAGE(
		"failed to create test subdirs",
		make_dirs(test_subsubdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is not a directory",
		is_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is a file",
		!is_file(test_subsubdir));
	CPPUNIT_ASSERT_MESSAGE(
		"created directory is not a directory",
		is_dir(test_subsubdir));

	{ // create file
		ofstream file(test_file);
		file << "hello" << endl;
	}
	CPPUNIT_ASSERT_MESSAGE(
		"failed to create test file",
		is_file(test_file));

	CPPUNIT_ASSERT_MESSAGE(
		"failed to remove test subdir",
		remove_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory became a file",
		!is_file(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory is still a directory",
		!is_dir(test_subdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory became a file",
		!is_file(test_subsubdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed directory is still a directory",
		!is_dir(test_subsubdir));
	CPPUNIT_ASSERT_MESSAGE(
		"removed file became a directory",
		!is_dir(test_file));
	CPPUNIT_ASSERT_MESSAGE(
		"removed file is still a file",
		!is_file(test_file));
}
Esempio n. 15
0
int main(int argc, char *argv[]) {
    const char *ext;
    int opt, line_length = DEFAULT_LINE_LENGTH;

#ifndef NDEBUG
    setbuf(stdout, NULL);
    setbuf(stderr, NULL);
#endif

    while ((opt = getopt(argc, argv, "fhl:nsv::V")) != -1) {
        switch(opt) {
            case 'f':
                config |= CONFIG_OVERWRITE;
                break;
            case 'h':
                usage(argv[0]);
                exit(EXIT_SUCCESS);
            case 'l':
                line_length = atoi(optarg);
                if (line_length <= 0 || line_length > MAX_LINE_LENGTH) {
                    fprintf(stderr, "Warning: incorrect line length. using the default %d.\n", DEFAULT_LINE_LENGTH);
                    line_length = DEFAULT_LINE_LENGTH;
                }
                break;
            case 'n':
                config &= ~CONFIG_BORDER;
                break;
            case 's':
                config &= ~CONFIG_COMMENT;
                break;
            case 'v':
                if (optarg == NULL) {
                    config |= CONFIG_VERBOSE;
                } else if (strcmp(optarg, "v") == 0) {
                    config |= CONFIG_VERBOSE | CONFIG_MORE_VERBOSE;
                } else {
                    fprintf(stderr, "Error: bad argument\n");
                    exit(EXIT_FAILURE);
                }
                break;
            case 'V':
                printf("%s\n", VERSION_STRING);
                exit(EXIT_SUCCESS);
            default:
                usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }

    /* line length is at minimum the BANNER_HEIGHT if there is a banner/border */
    if ((config & CONFIG_BORDER) && (line_length < BANNER_HEIGHT)) {
        fprintf(stderr, "Warning: line length should be at least the height of "
                "the hid.im logo i.e. %d\n", BANNER_HEIGHT);
        line_length = BANNER_HEIGHT;
    }
    if ((!(config & CONFIG_BORDER)) && (line_length < MIN_LINE_LENGTH)) {
        fprintf(stderr, "Warning: line length should be at least %d. using %d "
                "as line length\n", MIN_LINE_LENGTH, MIN_LINE_LENGTH);
        line_length = MIN_LINE_LENGTH;
    }

    if (optind >= argc) {
        fprintf(stderr, "Expected argument after options\n");
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    for (int i=optind; i<argc; i++) {
        if (!is_file(argv[i])) {
            fprintf(stderr, "Error: %s is not a file. skipped\n", argv[i]);
            continue;
        }

        ext = extension(argv[i]);
        if (ext == NULL) {
            fprintf(stderr, "Error: expecting files with .png or .torrent extension. %s skipped\n", argv[i]);
            continue;
        }
        char *ext_tolower = strtolower(ext);
        if (strcmp(ext_tolower, ".png") == 0) {
            decode(argv[i]);
        } else if (strcmp(ext_tolower, ".torrent") == 0) {
            encode(argv[i], line_length);
        } else {
            fprintf(stderr, "Error: files with .png or .torrent extension expected. %s skipped\n", argv[i]);
            free(ext_tolower);
            continue;
        }
        free(ext_tolower);
    }

    return EXIT_SUCCESS;
}
Esempio n. 16
0
Client* Client::connect(const char * conffile){
	static bool inited = false;
	if(!inited){
		inited = true;
		signal(SIGPIPE, SIG_IGN);
	}
	ClientImpl *client = new ClientImpl();
	Config * conf = NULL;
	char tmpbuf[64] = {0};
	char host[64] = {0};
	std::vector<Link*> vTmp;
	int nodesum = 0;

	static const char * default_conffile = "/usr/local/ssdb/ssdb_cli.conf";
	if ( conffile == NULL && conffile[0] == '\0' ) {
		conffile = default_conffile;
	}
	if ( !is_file(conffile) ) {
		fprintf( stderr, "'%s' is not a file or not exists!\n", conffile );
		goto CONNECTFAIL;
	}
	conf = Config::load( conffile );
	if ( conf == NULL ) {
		fprintf( stderr, "error loading conf file: '%s'\n", conffile );
		goto CONNECTFAIL;
	}

	nodesum = conf->get_num( "nodesum" );
	for ( int i = 0; i < nodesum; i++ ) {
		snprintf( tmpbuf, sizeof(tmpbuf), "node%d.hostsum", i );
		int hostsum = conf->get_num( tmpbuf );
		vTmp.clear();
		for ( int j = 0; j < hostsum; j++ ) {
			snprintf( tmpbuf, sizeof(tmpbuf), "node%d.host%d", i, j );
			strncpy( host, conf->get_str( tmpbuf ), sizeof(host)-1 );
			char * p = strchr( host, ':' );
			if ( p == NULL ) {
				fprintf( stderr, "host %s in '%s' format err\n", host, conffile );
				goto CONNECTFAIL;
			}
			*p = '\0';
			Link * link = Link::connect( host, atoi(p+1) );
			if ( link == NULL ) {
				fprintf( stderr, "host %s in '%s' connect err", host, conffile );
				goto CONNECTFAIL;
			}
			vTmp.push_back( link );
			client->vLinks.push_back( link );
		}
		for ( size_t j = 0; j < vTmp.size(); j++ ) {
			for ( size_t k = 0; k < vTmp.size(); k++ ) {
				if ( j != k ) {
					client->mLinks[ vTmp[j] ].push_back( vTmp[k] );
				}
			}
		}
	}

	if ( conf ) {
		delete conf;
	}
	return client;

CONNECTFAIL:
	if ( client ) {
		delete client;
	}
	if ( conf ) {
		delete conf;
	}
	return NULL;
}
Esempio n. 17
0
void
state_diskutil_menu(struct i_fn_args *a)
{
	struct dfui_form *f;
	struct dfui_action *k;
	struct dfui_response *r;
	int done = 0;

	while (!done) {
		f = dfui_form_create(
		    "utilities_menu",
		    _("Disk Utilities Menu"),
		    _("These functions let you manipulate the storage devices "
		    "attached to this computer."),
		    "",

		    "p", "role", "menu",

		    "a", "format_hdd",
		    _("Format a hard disk drive"), "", "",
		    "a", "wipe_start_of_disk",
		    _("Wipe out the start of a disk"), "", "",
		    "a", "wipe_start_of_slice",
		    _("Wipe out the start of a primary partition"), "", "",
		    "a", "install_bootblocks",
		    _("Install bootblocks on disks"), "", "",
		    "a", "format_msdos_floppy",
		    _("Format an MSDOS floppy"), "", "",
		    NULL
		);

		if (is_file("%sboot/cdboot.flp.bz2", a->os_root)) {
			dfui_form_action_add(f, "create_cdboot_floppy",
			    dfui_info_new(_("Create a CDBoot floppy"),
			    "",
			    ""));
		}

		k = dfui_form_action_add(f, "cancel",
		    dfui_info_new(_("Return to Utilities Menu"), "", ""));
		dfui_action_property_set(k, "accelerator", "ESC");

		if (!dfui_be_present(a->c, f, &r))
			abort_backend();

		/* XXX set up a */
		if (strcmp(dfui_response_get_action_id(r), "format_hdd") == 0) {
			storage_set_selected_disk(a->s, NULL);
			storage_set_selected_slice(a->s, NULL);
			fn_format_disk(a);
		} else if (strcmp(dfui_response_get_action_id(r), "wipe_start_of_disk") == 0) {
			fn_wipe_start_of_disk(a);
		} else if (strcmp(dfui_response_get_action_id(r), "wipe_start_of_slice") == 0) {
			fn_wipe_start_of_slice(a);
		} else if (strcmp(dfui_response_get_action_id(r), "install_bootblocks") == 0) {
			a->short_desc = _("Select the disks on which "
			    "you wish to install bootblocks.");
			a->cancel_desc = _("Return to Utilities Menu");
			fn_install_bootblocks(a, NULL);
		} else if (strcmp(dfui_response_get_action_id(r), "format_msdos_floppy") == 0) {
			fn_format_msdos_floppy(a);
		} else if (strcmp(dfui_response_get_action_id(r), "create_cdboot_floppy") == 0) {
			fn_create_cdboot_floppy(a);
		} else if (strcmp(dfui_response_get_action_id(r), "cancel") == 0) {
			state = state_utilities_menu;
			done = 1;
		}

		dfui_form_free(f);
		dfui_response_free(r);
	}
}
Esempio n. 18
0
static wchar_t* readlink(wchar_t* path)
{
	size_t szbuf = 0;
	wchar_t* result = path;
	char* cygbuf = NULL;
	byte* buffer = NULL;
	pcyglink slink = NULL;
	
	verbose(L"Checking %s for symbolic link..", path);
	
	// Make sure path is a file flagged as a system file.
	if(!is_file(path) || !has_system_attr(path)) goto cleanup;
	
	// Allocate our buffer and read the file into it.
	buffer = file_to_buffer(path, &szbuf);
	
	// Check if our buffer contains a symbolic link.
	if(!is_buf_symlink(buffer, szbuf)) goto cleanup;
	
	// If we get to this point, we're definitely working
	// with a symbolic link, so cast it to the struct.
	verbose(L"Detected symbolic link..");
	slink = (pcyglink)buffer;
	
	// Get the string length of our link's target.
	szbuf = wcslen(slink->target);
	if(szbuf == 0) {
		fatal(1, L"Empty path found as target of the symbolic link at %s.", path);
	}
	
	// Before converting it, we need to check whether it's a relative
	// or absolute file path.
	if(slink->target[0] != L'/') {
		verbose(L"Symbolic link target resolved to a relative path. Prefixing bin dir..");
		virtRootCyg = fix_path(virtRootWin);
		// len(virtualenv root) + len('/bin/') + len(target)
		szbuf += wcslen(virtRootCyg) + 5;
		result = walloc(szbuf++);
		swprintf(result, szbuf, L"%s/bin/%s", virtRootCyg, slink->target);
	} else {
		// Duping it to allow freeing the memory a few
		// lines later without issue.
		verbose(L"Symbolic link target appears to be an absolute path. Continuing..");
		result = _wcsdup(slink->target);
	}
	
	// Convert it to a ANSI string to allow converting
	// it with cygwin.
	cygbuf = xalloc(szbuf, sizeof(char));
	wcstombs(cygbuf, result, szbuf+1);
	xfree(result);
	if(!(result = fix_path_type((void*)cygbuf, false, CCP_POSIX_TO_WIN_A))) {
		result = path;
		goto cleanup;
	}
	verbose_step(L"readlink(x)");
	verbose_step(L"  x -> %s", path);
	verbose_step(L"  r <- %s", result);
cleanup:
	xfree(buffer);
	xfree(cygbuf);
	#ifdef WITHOUT_ENVVARS
	xfree(virtRootCyg);
	#endif
	return result;
}
Esempio n. 19
0
bool file_exists (const char* fname)
{
    return is_file (fname);
}
Esempio n. 20
0
int _singularity_runtime_mount_binds(void) {
    char *tmp_config_string;
    char *container_dir = singularity_runtime_rootfs(NULL);

    if ( singularity_registry_get("CONTAIN") != NULL ) {
        singularity_message(DEBUG, "Skipping bind mounts as contain was requested\n");
        return(0);
    }

    singularity_message(DEBUG, "Checking configuration file for 'bind path'\n");
    const char **tmp_config_string_list = singularity_config_get_value_multi(BIND_PATH);
    if ( strlength(*tmp_config_string_list, 1) == 0 ) {
        return(0);
    }
    while ( *tmp_config_string_list != NULL ) {
        tmp_config_string = strdup(*tmp_config_string_list);
        tmp_config_string_list++;
        char *source = strtok(tmp_config_string, ":");
        char *dest = strtok(NULL, ":");
        chomp(source);
        if ( dest == NULL ) {
            dest = strdup(source);
        } else {
            chomp(dest);
        }

        singularity_message(VERBOSE2, "Found 'bind path' = %s, %s\n", source, dest);

        if ( ( is_file(source) < 0 ) && ( is_dir(source) < 0 ) ) {
            singularity_message(WARNING, "Non existent 'bind path' source: '%s'\n", source);
            continue;
        }

        singularity_message(DEBUG, "Checking if bind point is already mounted: %s\n", dest);
        if ( check_mounted(dest) >= 0 ) {
            singularity_message(VERBOSE, "Not mounting bind point (already mounted): %s\n", dest);
            continue;
        }

        if ( ( is_file(source) == 0 ) && ( is_file(joinpath(container_dir, dest)) < 0 ) ) {
            if ( singularity_registry_get("OVERLAYFS_ENABLED") != NULL ) {
                char *basedir = dirname(joinpath(container_dir, dest));

                singularity_message(DEBUG, "Checking base directory for file %s ('%s')\n", dest, basedir);
                if ( is_dir(basedir) != 0 ) {
                    singularity_message(DEBUG, "Creating base directory for file bind\n");
                    singularity_priv_escalate();
                    if ( s_mkpath(basedir, 0755) != 0 ) {
                        singularity_message(ERROR, "Failed creating base directory to bind file: %s\n", dest);
                        ABORT(255);
                    }
                    singularity_priv_drop();
                }

                free(basedir);

                singularity_priv_escalate();
                singularity_message(VERBOSE3, "Creating bind file on overlay file system: %s\n", dest);
                FILE *tmp = fopen(joinpath(container_dir, dest), "w+"); // Flawfinder: ignore
                singularity_priv_drop();
                if ( tmp == NULL ) {
                    singularity_message(WARNING, "Could not create bind point file in container %s: %s\n", dest, strerror(errno));
                    continue;
                }
                if ( fclose(tmp) != 0 ) {
                    singularity_message(WARNING, "Could not close bind point file descriptor %s: %s\n", dest, strerror(errno));
                    continue;
                }
                singularity_message(DEBUG, "Created bind file: %s\n", dest);
            } else {
                singularity_message(WARNING, "Non existent bind point (file) in container: '%s'\n", dest);
                continue;
            }
        } else if ( ( is_dir(source) == 0 ) && ( is_dir(joinpath(container_dir, dest)) < 0 ) ) {
            if ( singularity_registry_get("OVERLAYFS_ENABLED") != NULL ) {
                singularity_priv_escalate();
                singularity_message(VERBOSE3, "Creating bind directory on overlay file system: %s\n", dest);
                if ( s_mkpath(joinpath(container_dir, dest), 0755) < 0 ) {
                    singularity_priv_drop();
                    singularity_message(WARNING, "Could not create bind point directory in container %s: %s\n", dest, strerror(errno));
                    continue;
                }
                singularity_priv_drop();
            } else {
                singularity_message(WARNING, "Non existent bind point (directory) in container: '%s'\n", dest);
                continue;
            }
        }

        singularity_priv_escalate();
        singularity_message(VERBOSE, "Binding '%s' to '%s/%s'\n", source, container_dir, dest);
        if ( mount(source, joinpath(container_dir, dest), NULL, MS_BIND|MS_NOSUID|MS_REC, NULL) < 0 ) {
            singularity_message(ERROR, "There was an error binding the path %s: %s\n", source, strerror(errno));
            ABORT(255);
        }
        if ( singularity_priv_userns_enabled() != 1 ) {
            if ( mount(NULL, joinpath(container_dir, dest), NULL, MS_BIND|MS_NOSUID|MS_REC|MS_REMOUNT, NULL) < 0 ) {
                singularity_message(ERROR, "There was an error remounting the path %s: %s\n", source, strerror(errno));
                ABORT(255);
            }
        }
        singularity_priv_drop();
    }

    return(0);
}
Esempio n. 21
0
void init(int argc, char **argv)
{


	const char* conf_file = "chatserv.conf";
	if (!is_file(conf_file)){
		fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
#ifdef _DEBUG
		system("pause");
#endif
		//exit(0);
	}

	conf = Config::load(conf_file);
	if (!conf){
		fprintf(stderr, "error loading conf file: '%s'\n", conf_file);
#ifdef _DEBUG
		system("pause");
#endif
		exit(0);
	}
	else
	{
		fprintf(stderr, "loading conf file success: '%s'\n", conf_file);
	}
	std::string log_output;
	int log_rotate_size = 0;
	{ // logger
		int log_level = Logger::get_level(conf->get_str("logger.level"));
		log_rotate_size = conf->get_num("logger.rotate.size");
		if (log_rotate_size < 1024 * 1024){
			log_rotate_size = 1024 * 1024;
		}
		log_output = conf->get_str("logger.output");
		if (log_output == ""){
			log_output = "stdout";
		}
		if (log_open(log_output.c_str(), log_level, true, log_rotate_size) == -1){
			fprintf(stderr, "error open log file: %s\n", log_output.c_str());
#ifdef _DEBUG
			system("pause");
#endif
			exit(0);
		}

		log_info("starting chatserv %s...", CHATSERV_VERSION);
		log_info("config file: %s", conf_file);
		log_info("log_level       : %s", conf->get_str("logger.level"));
		log_info("log_output      : %s", log_output.c_str());
		log_info("log_rotate_size : %d", log_rotate_size);

		WSADATA wsa = { 0 };
		int wsaStartup=WSAStartup(MAKEWORD(2, 2), &wsa);
		if (wsaStartup != 0)
		{
			log_error("failed to initialize WSAStartup:%d", wsaStartup);
			exit(0);
		}
		log_info("WSAStartup success :%d", wsaStartup);
		evbase = event_base_new();
		if (!evbase){
			fprintf(stderr, "create evbase error!\n");
			exit(0);
		}
		log_info("evbase created");
		admin_http = evhttp_new(evbase);
		if (!admin_http){
			fprintf(stderr, "create admin_http error!\n");
			exit(0);
		}
		log_info("admin_http created");
		front_http = evhttp_new(evbase);
		if (!front_http){
			fprintf(stderr, "create front_http error!\n");
			exit(0);
		}
		log_info("front_http created");

		sigint_event = evsignal_new(evbase, SIGINT, signal_cb, NULL);
		if (!sigint_event || event_add(sigint_event, NULL) < 0){
			fprintf(stderr, "Could not create/add a signal event!\n");
			exit(0);
		}
		log_info("sigint_event created/added");
		sigterm_event = evsignal_new(evbase, SIGTERM, signal_cb, NULL);
		if (!sigterm_event || event_add(sigterm_event, NULL) < 0){
			fprintf(stderr, "Could not create/add a signal event!\n");
			exit(0);
		}
		log_info("sigterm_event created/added");
		timer_event = event_new(evbase, -1, EV_PERSIST, timer_cb, NULL);
		{
			//用于检测无效的连接
			struct timeval tv;
			tv.tv_sec = CHANNEL_CHECK_INTERVAL;
			tv.tv_usec = 0;
			if (!timer_event || evtimer_add(timer_event, &tv) < 0){
				fprintf(stderr, "Could not create/add a timer event!\n");
				exit(0);
			}
			log_info("timer event added");
		}
	}

}
Esempio n. 22
0
int main (int argc, char *argv[]) {
    setpgrp();  // Become the leader of its group.
    // Child's CMD line
    int m = sysconf(_SC_ARG_MAX);           // Maximum CMD line length
    char *cmd;                              // Store child's CMD line
    cmd = (char *) calloc(m, sizeof(char));

    // Child's parameters
    int *child_delay = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    *child_delay = 0;                       // Delay before starting (shared between parent and child)
    int child_pid = -1;                     // PID after the fork()
    int child_status = -1;                  // Used during waitpid()
    char *child_file = NULL;                // Binary file

    // Telnet server
    int ts_port = -1;                       // TCP (console) and UDP (serial converter) port
    char *xtitle = "Terminal Server";       // Title for telnet clients

    // Select parameters
    int *infd = calloc(2, sizeof(int));     // Array of integers [0] is for reading, [1] is for writing
    int *outfd = calloc(2, sizeof(int));    // Array of integers [0] is for reading, [1] is for writing
    fd_set active_fd_set;                   // Contains active FD using in select()
    FD_ZERO(&active_fd_set);
    fd_set read_fd_set;                     // Contains FD selected in current loop
    FD_ZERO(&read_fd_set);

    // Other parameters
    int i = -1;                             // Counter
    int j = -1;                             // Counter
    int opt = NULL;                         // Store CMD options
    int rc = -1;                            // Generic return code
    char *tmp = NULL;                       // Generic char string
    struct sigaction sa;                    // Manage signals (SIGHUP, SIGTERM...)

    // Wrapper parameters
    int child_afsocket[100];                // Store AF_UNIX child sockets
    memset(&child_afsocket, 0, sizeof(child_afsocket));
    int ser_remoteid[64];                   // Store Remote Device ID (used for UDP communication)
    memset(&ser_remoteid, 0, sizeof(ser_remoteid));
    int ser_remoteif[64];                   // Store Remote Interface ID (used for UDP communication)
    memset(&ser_remoteif, 0, sizeof(ser_remoteif));
    int udpserver_socket = -1;              // UDP socket for serial communications
    int wrapper_afsocket[100];              // Store AF_UNIX wrapper sockets
    memset(&wrapper_afsocket, 0, sizeof(wrapper_afsocket));

    // Parsing options
    while ((opt = getopt(argc, argv, ":vT:D:d:t:F:x")) != -1) {
        switch (opt) {
            default:
                usage(argv[0]);
                exit(1);
            // Begin standard parameters
            case 'v':
                printf("%s\n", VERSION);
                exit(0);
            case 'T':
                // Mandatory: Tenant ID
                tenant_id = atoi(optarg);
                if (tenant_id < 0) {
                    UNLLog(LLERROR,"Tenant_id must be integer.\n");
                    exit(1);
                }
                UNLLog(LLINFO, "Tennant_id = %i\n", tenant_id);
                break;
            case 'D':
                // Mandatory: Device ID
                device_id = atoi(optarg);
                if (tenant_id < 0) {
                    UNLLog(LLERROR,"Device_id must be integer.\n");
                    exit(1);
                }
                UNLLog(LLINFO, "Device_id = %i\n", device_id);
                break;
            case 'F':
                // Mandatory: IOS
                child_file = optarg;
                if (is_file(child_file) != 0) {
                    UNLLog(LLERROR,"File '%s' does not exist.\n", child_file);
                    exit(1);
                }
                break;
            case 'd':
                // Optional: child's startup delay (default 0)
                *child_delay = atoi(optarg);
                if (*child_delay < 0) {
                    UNLLog(LLERROR,"Delay must be integer.\n");
                    exit(1);
                }
                break;
            case 't':
                // Optional: telnet window title (default "Terminal Server")
                xtitle = optarg;
                break;
        }
    }

    // Checking if tenant_id is set
    if (tenant_id < 0) {
        UNLLog(LLERROR,"Tenant ID not set.\n");
        exit(1);
    }

    // Checking if device_id is set
    if (device_id < 0) {
        UNLLog(LLERROR,"Device ID not set.\n");
        exit(1);
    }

    // Checking if child_file is set
    if (child_file == NULL) {
        UNLLog(LLERROR,"Subprocess executable not set.\n");
        exit(1);
    }

    // Building the CMD line
    ts_port = 32768 + 128 * tenant_id + device_id;
    tmp = (char *) malloc(m * sizeof(char));
    sprintf(tmp, "/usr/bin/dynamips -N '%s' -T %i", xtitle, ts_port);
    cmd_add(&cmd, tmp);
    free(tmp);

    // Adding parameters after "--"
    j = 0;
    for (i = 1; i < argc; i++) {
        if (j == 1) {
            // Adding parameter given after "--"
            cmd_add(&cmd, " ");
            cmd_add(&cmd, argv[i]);
        }
        if (strcmp(argv[i], "--") == 0) {
            // Found "--"
            j = 1;
        }
    }

    // Adding the IOS filename
    cmd_add(&cmd, " ");
    cmd_add(&cmd, child_file);

    // Creating PIPEs for select()
    if ((pipe(infd)) < 0 || pipe(outfd) < 0) {
         UNLLog(LLERROR, "Failed to create PIPEs (%s).\n", strerror(errno));
         exit(1);
    }

    // Forking
    if ((rc = fork()) == 0) {
        // Child: stating subprocess
        UNLLog(LLINFO, "Starting child (%s).\n", cmd);
        if (*child_delay > 0) {
            // Delay is set, waiting
            for (; *child_delay > 0;) {
                rc = write(outfd[1], ".", 1);
                *child_delay = *child_delay - 1;
                sleep(1);
            }
            rc = write(outfd[1], "\n", 1);
        }
        close(STDIN_FILENO);            // Closing child's stdin
        close(STDOUT_FILENO);           // Closing child's stdout
        dup2(infd[0], STDIN_FILENO);    // Linking stdin to PIPE
        dup2(outfd[1], STDOUT_FILENO);  // Linking stdout to PIPE
        dup2(outfd[1], STDERR_FILENO);  // Redirect child's stderr to child's stdout
        close(infd[0]);
        close(infd[1]);
        close(outfd[0]);
        close(outfd[1]);
        // Start process
        rc = cmd_start(cmd);
        // Subprocess terminated, killing the parent
        UNLLog(LLERROR,"Child terminated (%i).\n", rc);
    } else if (rc > 0) {
        // Parent
        close(infd[0]);                     // Used by the child
        close(outfd[1]);                    // Used by the child

        // Handling Signals
        signal(SIGPIPE,SIG_IGN);            // Ignoring SIGPIPE when a client terminates
        sa.sa_handler = &signal_handler;    // Setup the sighub handler
        sa.sa_flags = SA_RESTART;           // Restart the system call, if at all possible
        sigemptyset(&sa.sa_mask);           // Signals blocked during the execution of the handler
        sigaddset(&sa.sa_mask, SIGHUP);     // Signal 1
        sigaddset(&sa.sa_mask, SIGINT);     // Signal 2
        sigaddset(&sa.sa_mask, SIGTERM);    // Signal 15
        sigfillset(&sa.sa_mask);

        // Intercept SIGHUP, SIGINT, SIGUSR1 and SIGTERM
        if (sigaction(SIGHUP, &sa, NULL) == -1) {
            UNLLog(LLERROR, "Cannot handle SIGHUP (%s).\n", strerror(errno));
        }
        if (sigaction(SIGINT, &sa, NULL) == -1) {
            UNLLog(LLERROR, "Cannot handle SIGINT (%s).\n", strerror(errno));
        }
        if (sigaction(SIGTERM, &sa, NULL) == -1) {
            UNLLog(LLERROR, "Cannot handle SIGTERM (%s).\n", strerror(errno));
        }

        // Preparing select()
        FD_ZERO(&active_fd_set);
        FD_ZERO(&read_fd_set);
        if (udpserver_socket > 0) {
            FD_SET(udpserver_socket, &active_fd_set); // Adding UDP socket
        }

        // While subprocess is running, check IO from subprocess, telnet clients, socket and network
        waitpid(child_pid, &child_status, 0);
        // Child is no more running
        UNLLog(LLERROR, "Child is no more running.\n");
    } else {
        UNLLog(LLERROR, "Failed to fork (%s).\n", strerror(errno));
        exit(1);
    }
    exit(0);
}
Esempio n. 23
0
int main (int argc, char **argv)
{
    int write_flag = 0, config_flag = 0;

    // Set locale and message catalogs.
    setlocale (LC_ALL, "");
#ifdef MINGW32
    // Files with localized messages should be placed in
    // in c:/Program Files/baoclone/ directory.
    bindtextdomain ("baoclone", "c:/Program Files/baoclone");
#else
    bindtextdomain ("baoclone", "/usr/local/share/locale");
#endif
    textdomain ("baoclone");

    copyright = _("Copyright (C) 2013-2018 Serge Vakulenko KK6ABQ");
    verbose = 0;
    for (;;) {
        switch (getopt (argc, argv, "vcw")) {
        case 'v': ++verbose;     continue;
        case 'w': ++write_flag;  continue;
        case 'c': ++config_flag; continue;
        default:
            usage ();
        case EOF:
            break;
        }
        break;
    }
    argc -= optind;
    argv += optind;
    if (write_flag + config_flag > 1) {
        fprintf (stderr, "Only one of -w or -c options is allowed.\n");
        usage();
    }
    setvbuf (stdout, 0, _IOLBF, 0);
    setvbuf (stderr, 0, _IOLBF, 0);

    if (write_flag) {
        // Restore image file to device.
        if (argc != 2)
            usage();

        radio_connect (argv[0]);
        radio_read_image (argv[1]);
        radio_print_version (stdout);
        radio_upload (0);
        radio_disconnect();

    } else if (config_flag) {
        if (argc != 2)
            usage();

        if (is_file (argv[0])) {
            // Apply text config to image file.
            radio_read_image (argv[0]);
            radio_print_version (stdout);
            radio_parse_config (argv[1]);
            radio_save_image ("device.img");

        } else {
            // Update device from text config file.
            radio_connect (argv[0]);
            radio_download();
            radio_print_version (stdout);
            radio_save_image ("backup.img");
            radio_parse_config (argv[1]);
            radio_upload (1);
            radio_disconnect();
        }

    } else {
        if (argc != 1)
            usage();

        if (is_file (argv[0])) {
            // Print configuration from image file.
            // Load image from file.
            radio_read_image (argv[0]);
            radio_print_version (stdout);
            radio_print_config (stdout, ! isatty (1));

        } else {
            // Dump device to image file.
            radio_connect (argv[0]);
            radio_download();
            radio_print_version (stdout);
            radio_disconnect();
            radio_save_image ("device.img");

            // Print configuration to file.
            const char *filename = "device.conf";
            printf ("Print configuration to file '%s'.\n", filename);
            FILE *conf = fopen (filename, "w");
            if (! conf) {
                perror (filename);
                exit (-1);
            }
            radio_print_version (conf);
            radio_print_config (conf, 1);
            fclose (conf);
        }
    }
    return (0);
}
Esempio n. 24
0
File: main.c Progetto: buaazp/zimg
/**
 * @brief main The entrance of zimg.
 *
 * @param argc Count of args.
 * @param argv Arg list.
 *
 * @return It returns a int to system.
 */
int main(int argc, char **argv) {
    /* Set signal handlers */
    sigset_t sigset;
    sigemptyset(&sigset);
    struct sigaction siginfo = {
        .sa_sigaction = &sighandler,
        .sa_mask = sigset,
        .sa_flags = SA_RESTART,
    };
    sigaction(SIGINT, &siginfo, NULL);
    sigaction(SIGTERM, &siginfo, NULL);

    if (argc < 2) {
        usage(argc, argv);
        return -1;
    }

    settings_init();
    int i;
    for (i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-d") == 0) {
            settings.is_daemon = 1;
        } else {
            conf_file = argv[i];
        }
    }

    if (conf_file == NULL) {
        usage(argc, argv);
        return -1;
    }

    if (is_file(conf_file) == -1) {
        fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
        return -1;
    }

    if (load_conf(conf_file) == -1) {
        fprintf(stderr, "'%s' load failed!\n", conf_file);
        return -1;
    }

    if (bind_check(settings.port) == -1) {
        fprintf(stderr, "Port %d bind failed!\n", settings.port);
        return -1;
    }

    if (settings.is_daemon == 1) {
        if (daemon(1, 1) < 0) {
            fprintf(stderr, "Create daemon failed!\n");
            return -1;
        } else {
            fprintf(stdout, "zimg %s\n", settings.version);
            fprintf(stdout, "Copyright (c) 2013-2014 zimg.buaa.us\n");
            fprintf(stderr, "\n");
        }
    }
    //init the Path zimg need to use.
    //start log module... ./log/zimg.log
    if (mk_dirf(settings.log_name) != 1) {
        fprintf(stderr, "%s log path create failed!\n", settings.log_name);
        return -1;
    }
    log_init();

    if (settings.script_name[0] != '\0') {
        if (is_file(settings.script_name) == -1) {
            fprintf(stderr, "%s open failed!\n", settings.script_name);
            return -1;
        }
        settings.script_on = 1;
    }

    if (is_dir(settings.img_path) != 1) {
        if (mk_dirs(settings.img_path) != 1) {
            LOG_PRINT(LOG_DEBUG, "img_path[%s] Create Failed!", settings.img_path);
            fprintf(stderr, "%s Create Failed!\n", settings.img_path);
            return -1;
        }
    }
    LOG_PRINT(LOG_DEBUG, "Paths Init Finished.");

    if (settings.mode == 2) {
        LOG_PRINT(LOG_DEBUG, "Begin to Test Memcached Connection...");
        memcached_st *beans = memcached_create(NULL);
        char mserver[32];
        snprintf(mserver, 32, "%s:%d", settings.beansdb_ip, settings.beansdb_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);
        servers = memcached_servers_parse(mserver);
        memcached_server_push(beans, servers);
        memcached_server_list_free(servers);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_NO_BLOCK, 1);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1);
        LOG_PRINT(LOG_DEBUG, "beansdb Connection Init Finished.");
        if (set_cache(beans, "zimg", "1") == -1) {
            LOG_PRINT(LOG_DEBUG, "Beansdb[%s] Connect Failed!", mserver);
            fprintf(stderr, "Beansdb[%s] Connect Failed!\n", mserver);
            memcached_free(beans);
            return -1;
        } else {
            LOG_PRINT(LOG_DEBUG, "beansdb connected to: %s", mserver);
        }
        memcached_free(beans);
    } else if (settings.mode == 3) {
        redisContext* c = redisConnect(settings.ssdb_ip, settings.ssdb_port);
        if (c->err) {
            redisFree(c);
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server faile");
            fprintf(stderr, "SSDB[%s:%d] Connect Failed!\n", settings.ssdb_ip, settings.ssdb_port);
            return -1;
        } else {
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server Success");
        }
    }

    //init magickwand
    MagickCoreGenesis((char *) NULL, MagickFalse);
    /*
    ExceptionInfo *exception=AcquireExceptionInfo();
    MagickInfo *jpeg_info = (MagickInfo *)GetMagickInfo("JPEG", exception);
    if(jpeg_info->thread_support != MagickTrue)
        LOG_PRINT(LOG_DEBUG, "thread_support != MagickTrue");
    jpeg_info->thread_support = MagickTrue;
    if(jpeg_info->thread_support != MagickTrue)
        LOG_PRINT(LOG_DEBUG, "thread_support != MagickTrue");
    MagickInfo *jpg_info = (MagickInfo *)GetMagickInfo("JPG", exception);
    jpg_info->thread_support = MagickTrue;
    */

    int result = pthread_key_create(&gLuaStateKey, thread_lua_dtor);
    if (result != 0) {
        LOG_PRINT(LOG_ERROR, "Could not allocate TLS key for lua_State.");
    }

    //begin to start httpd...
    LOG_PRINT(LOG_DEBUG, "Begin to Start Httpd Server...");
    LOG_PRINT(LOG_INFO, "zimg started");
    evbase = event_base_new();
    evhtp_t *htp = evhtp_new(evbase, NULL);

    evhtp_set_cb(htp, "/dump", dump_request_cb, NULL);
    evhtp_set_cb(htp, "/upload", post_request_cb, NULL);
    evhtp_set_cb(htp, "/admin", admin_request_cb, NULL);
    evhtp_set_cb(htp, "/info", info_request_cb, NULL);
    evhtp_set_cb(htp, "/echo", echo_cb, NULL);
    evhtp_set_gencb(htp, get_request_cb, NULL);
#ifndef EVHTP_DISABLE_EVTHR
    evhtp_use_threads(htp, init_thread, settings.num_threads, NULL);
#endif
    evhtp_set_max_keepalive_requests(htp, settings.max_keepalives);
    evhtp_bind_socket(htp, settings.ip, settings.port, settings.backlog);

    event_base_loop(evbase, 0);

    evhtp_unbind_socket(htp);
    //evhtp_free(htp);
    event_base_free(evbase);
    free_headers_conf(settings.headers);
    free_access_conf(settings.up_access);
    free_access_conf(settings.down_access);
    free_access_conf(settings.admin_access);
    free(settings.mp_set);

    return 0;
}
/* check_rc_trojans:
 * Read the file pointer specified (rootkit_trojans)
 * and check if the any trojan entry is on the configured files
 */
void check_rc_trojans(char *basedir, FILE *fp)
{
    int i = 0, _errors = 0, _total = 0;
    char buf[OS_SIZE_1024 +1];
    char file_path[OS_SIZE_1024 +1];

    char *file;
    char *string_to_look;

    #ifndef WIN32
    char *(all_paths[]) = {"bin","sbin","usr/bin","usr/sbin", NULL};
    #else
    char *(all_paths[]) = {"C:\\Windows\\", "D:\\Windows\\", NULL};
    #endif

    debug1("%s: DEBUG: Starting on check_rc_trojans", ARGV0);


    while(fgets(buf, OS_SIZE_1024, fp) != NULL)
    {
        char *nbuf;
        char *message = NULL;

        i = 0;

        /* Removing end of line */
        nbuf = strchr(buf, '\n');
        if(nbuf)
        {
            *nbuf = '\0';
        }


        /* Normalizing line */
        nbuf = normalize_string(buf);
        

        if(*nbuf == '\0' || *nbuf == '#')
        {
            continue;
        }


        /* File now may be valid */
        file = nbuf;

        string_to_look = strchr(file, '!');
        if(!string_to_look)
        {
            continue;
        }
        
        *string_to_look = '\0';
        string_to_look++;

        message = strchr(string_to_look, '!');
        if(!message)
        {
            continue;
        }
        *message = '\0';
        message++;
        
        string_to_look = normalize_string(string_to_look);
        file = normalize_string(file);
        message = normalize_string(message);
        
        
        if(*file == '\0' || *string_to_look == '\0')
        {
            continue;
        }
        
        _total++;
        
        
        /* Trying with all possible paths */
        while(all_paths[i] != NULL)
        {
            if(*file != '/')
            {
                snprintf(file_path, OS_SIZE_1024, "%s/%s/%s",basedir, 
                        all_paths[i],
                        file);
            }
            else
            {
                strncpy(file_path, file, OS_SIZE_1024);
                file_path[OS_SIZE_1024 -1] = '\0';
            }
            
            /* Checking if entry is found */
            if(is_file(file_path) && os_string(file_path, string_to_look))
            {
                char op_msg[OS_SIZE_1024 +1];
                _errors = 1;
            
                snprintf(op_msg, OS_SIZE_1024, "Trojaned version of file "
                        "'%s' detected. Signature used: '%s' (%s).", 
                                        file_path,
                                        string_to_look,
                                        *message == '\0'?
                                        "Generic":message);

                notify_rk(ALERT_ROOTKIT_FOUND, op_msg);
            }

            if(*file == '/')
            {
                break;
            }
            i++;
        }
        continue;        
    }


    if(_errors == 0)
    {
        char op_msg[OS_SIZE_1024 +1];
        snprintf(op_msg,OS_SIZE_1024, "No binaries with any trojan detected. "
                                    "Analyzed %d files.", _total);
        notify_rk(ALERT_OK, op_msg);
    }
}
Esempio n. 26
0
/**
 * Check if the argument provided is a (regular) file and is readable by user calling
 *
 * @param path to the file to check
 * @return true is it's a regular and is readable, false otherwise
 */
bool is_readable_file(char* path)
{
	return is_file(path) && access(path, R_OK)==0;
}
Esempio n. 27
0
/* Compresses a file `f_src' and saves it as `f_target'.
 */
static int compress_to_file(char *f_src, char *f_target, int mode_num)
{
  char buf[BUFLEN], mode[5];
  FILE *fin, *fout;
  int len;

  adjust_mode_num(&mode_num);
  egg_snprintf(mode, sizeof mode, "wb%d", mode_num);

  if (!is_file(f_src)) {
    putlog(LOG_MISC, "*", "Failed to compress file `%s': not a file.", f_src);
    return COMPF_ERROR;
  }
  fin = fopen(f_src, "rb");
  if (!fin) {
    putlog(LOG_MISC, "*", "Failed to compress file `%s': open failed: %s.",
           f_src, strerror(errno));
    return COMPF_ERROR;
  }

  fout = gzopen(f_target, mode);
  if (!fout) {
    putlog(LOG_MISC, "*", "Failed to compress file `%s': gzopen failed.",
           f_src);
    return COMPF_ERROR;
  }

#ifdef HAVE_MMAP
  if (compress_to_file_mmap(fout, fin) == COMPF_SUCCESS) {
    compressed_files++;
    return COMPF_SUCCESS;
  } else {
    /* To be on the safe side, close the file before attempting
     * to write again.
     */
    gzclose(fout);
    fout = gzopen(f_target, mode);
  }
#endif /* HAVE_MMAP */

  while (1) {
    len = fread(buf, 1, sizeof(buf), fin);
    if (ferror(fin)) {
      putlog(LOG_MISC, "*", "Failed to compress file `%s': fread failed: %s",
             f_src, strerror(errno));
      return COMPF_ERROR;
    }
    if (!len)
      break;
    if (gzwrite(fout, buf, (unsigned int) len) != len) {
      putlog(LOG_MISC, "*", "Failed to compress file `%s': gzwrite failed.",
             f_src);
      return COMPF_ERROR;
    }
  }
  fclose(fin);
  if (gzclose(fout) != Z_OK) {
    putlog(LOG_MISC, "*", "Failed to compress file `%s': gzclose failed.",
           f_src);
    return COMPF_ERROR;
  }
  compressed_files++;
  return COMPF_SUCCESS;
}
Esempio n. 28
0
/**
 * Check if the argument provided is a (regular) file and is writable by user calling
 *
 * @param path to the file to check
 * @return true is it's a regular and is writable, false otherwise
 */
bool is_writable_file(char* path)
{
	return is_file(path) && access(path, W_OK)==0;
}
Esempio n. 29
0
struct transport *transport_get(struct remote *remote, const char *url)
{
	const char *helper;
	struct transport *ret = xcalloc(1, sizeof(*ret));

	ret->progress = isatty(2);

	if (!remote)
		BUG("No remote provided to transport_get()");

	ret->got_remote_refs = 0;
	ret->remote = remote;
	helper = remote->foreign_vcs;

	if (!url && remote->url)
		url = remote->url[0];
	ret->url = url;

	/* maybe it is a foreign URL? */
	if (url) {
		const char *p = url;

		while (is_urlschemechar(p == url, *p))
			p++;
		if (starts_with(p, "::"))
			helper = xstrndup(url, p - url);
	}

	if (helper) {
		transport_helper_init(ret, helper);
	} else if (starts_with(url, "rsync:")) {
		die(_("git-over-rsync is no longer supported"));
	} else if (url_is_local_not_ssh(url) && is_file(url) && is_bundle(url, 1)) {
		struct bundle_transport_data *data = xcalloc(1, sizeof(*data));
		transport_check_allowed("file");
		ret->data = data;
		ret->vtable = &bundle_vtable;
		ret->smart_options = NULL;
	} else if (!is_url(url)
		|| starts_with(url, "file://")
		|| starts_with(url, "git://")
		|| starts_with(url, "ssh://")
		|| starts_with(url, "git+ssh://") /* deprecated - do not use */
		|| starts_with(url, "ssh+git://") /* deprecated - do not use */
		) {
		/*
		 * These are builtin smart transports; "allowed" transports
		 * will be checked individually in git_connect.
		 */
		struct git_transport_data *data = xcalloc(1, sizeof(*data));
		ret->data = data;
		ret->vtable = &builtin_smart_vtable;
		ret->smart_options = &(data->options);

		data->conn = NULL;
		data->got_remote_heads = 0;
	} else {
		/* Unknown protocol in URL. Pass to external handler. */
		int len = external_specification_len(url);
		char *handler = xmemdupz(url, len);
		transport_helper_init(ret, handler);
	}

	if (ret->smart_options) {
		ret->smart_options->thin = 1;
		ret->smart_options->uploadpack = "git-upload-pack";
		if (remote->uploadpack)
			ret->smart_options->uploadpack = remote->uploadpack;
		ret->smart_options->receivepack = "git-receive-pack";
		if (remote->receivepack)
			ret->smart_options->receivepack = remote->receivepack;
	}

	return ret;
}
Esempio n. 30
0
Move Notation::value(const Board & board, ColorType side, InputFormat format, const string &image) 
{
    int rank = 0;
    int file = 0;

    PieceType piece = Empty;
    PieceType promotion = Empty;
    Square dest = InvalidSquare, start = InvalidSquare;
    int capture = 0;

    stringstream s(image);
    string::const_iterator it = image.begin();
    int i = 0;
    while (it != image.end() && isspace(*it)) {
        it++;
        i++;
    }
    if (it == image.end() || !isalpha(*it)) return NullMove;
    string img(image,i); // string w/o leading spaces
    ASSERT(img.length());
    it = img.begin();
    if (*it == 'O' || *it == '0') {
       // castling, we presume
       return parseCastling(board, side, img);
    } else if (format == WB_IN) {
       if (img.length() < 4) return NullMove;
       Square start = SquareValue(img.substr(0,2));
       if (!OnBoard(start)) return NullMove;
       Square dest = SquareValue(img.substr(2,2));
       if (!OnBoard(dest)) return NullMove;
       PieceType promotion = Empty;
       if (img.length() > 4) {
          promotion = PieceCharValue(toupper(img[4]));
       }
       return CreateMove(board,start,dest,promotion);
    }
    int have_start = 0;
    if (isupper(*it)) {
       piece = PieceCharValue(*it);
       it++;
    }
    else {
       piece = Pawn;
       if ((it+1) != img.end()) {
          char next = *it;
          file = next-'a'+1;
          if (file < 1 || file > 8) return NullMove;
          char next2 = *(it+1);
          if (next2 == 'x' || is_file(next2)) {
             // allow "dc4" as in Informant, instead of dxc4
             it++;
             capture = 1;
          }
          else if (isdigit(next2) && img.length()>2) {
             char next3 = *(it+2);
             if ((next3 == 'x' || next3 == '-') && img.length()>=5) {
                // long algebraic notation
                have_start++;
                start = SquareValue(next,next2);
                if (start == InvalidSquare) return NullMove;
                it+=3; // point to dest
                piece = TypeOfPiece(board[start]);
             }
          }
       }
    }
    if (piece == Empty) {
       return NullMove;
    }
    if (piece != Pawn && !have_start && it != img.end()) {
       char next = *it;
       char next2 = '\0';
       if (it + 1 != img.end()) next2 = *(it+1);
       if (is_file(next) && isdigit(next2) && img.length()>=5) {
          // long algebraic notation, or a SAN move like Qd1d3
          start = SquareValue(next,next2);
          if (IsInvalid(start)) return NullMove;
          it+=2;
          have_start++;
       }
       // also look for disambiguating rank, e.g. '2' in "N2e4".
       else if (isdigit(next)) {
          rank = next - '0';
          if (rank < 1 || rank > 8) return NullMove;
          it++;
       }
       else if (is_file(next) && isalpha(next2)) {
          // disamiguating rank, e.g. "Rfd1"
          file = next - 'a' + 1;
          if (file < 1 || file > 8) return NullMove;
          it++;
       }
    }

    if (it != img.end() && *it == 'x') {
       capture = 1;
       it++;
    }
    if (it != img.end() && (it+1) != img.end()) {
       // remainder of move should be a square identifier, e.g. "g7"
       dest = SquareValue(*it,*(it+1));
       it += 2;
    }
    if (IsInvalid(dest)) {
       return NullMove;
    }
    if (it != img.end() && *it == '=') {
       it++;
       if (it == img.end()) {
          return NullMove;
       } else {
          promotion = PieceCharValue(*it);
          if (piece != Pawn || promotion == Empty)
             return NullMove;
          it++;
       }
    }
    else if (piece == Pawn && it != img.end() && isupper(*it)) {
       // Quite a few "PGN" files have a8Q instead of a8=Q.
       promotion = PieceCharValue(*it);
       if (promotion == Empty || Rank(dest,side) != 8)
          return NullMove;
    } else if (piece == Pawn && Rank(dest,side) == 8) {
       // promotion but no piece specified, treat as error
       return NullMove;
    }

    // Informant does not use "x" for captures.  Assume that if the destination
    // is occupied, this is a capture move.
    if (board[dest] != EmptyPiece) {
       capture = 1;
    }
    // Do a sanity check on capture moves:
    if (capture && !IsEmptyPiece(board[dest]) && PieceColor(board[dest]) == board.sideToMove()) {
       return NullMove;
    }

    // Ok, now we need to figure out where the start square is. For pawn
    // moves this is implicit.

    int dups = 0;

    if (!have_start) {
       if (capture && piece == Pawn && IsEmptyPiece(board[dest]) &&
           Rank(dest,board.sideToMove()) != 8) {
          // en passant capture, special case
          int start_rank = (board.sideToMove() == White) ?
             Rank(dest,White) - 1 :
             Rank(dest,White) + 1;

          start = MakeSquare(file, start_rank, White);
          dups = 1;
       }
       else if (piece == Pawn && board[dest] == EmptyPiece) {
          start = MakeSquare(file,Rank(dest,board.sideToMove())-1,board.sideToMove());
          if (board[start] == EmptyPiece && Rank(dest,board.sideToMove())==4) {
             start = MakeSquare(file,Rank(dest,board.sideToMove())-2,board.sideToMove());
          }
          if (board[start] == EmptyPiece) return NullMove;
          dups = 1;
       }
       else {
          Bitboard attacks = board.calcAttacks(dest,side);
          Square maybe;
          while (attacks.iterate(maybe)) {
             if (TypeOfPiece(board[maybe]) == piece &&
                 PieceColor(board[maybe]) == board.sideToMove()) {
                if (file && File(maybe) != file)
                   continue;
                if (rank && Rank(maybe,White) != rank)
                   continue;
                if (PieceColor(board[maybe]) == board.sideToMove()) {
                   // Possible move to this square.  Make sure it is legal.
                   Board board_copy(board);
                   Move emove = CreateMove(board,maybe,dest,
                                           promotion);
                   board_copy.doMove(emove);
                   if (!board_copy.anyAttacks(
                          board_copy.kingSquare(board_copy.oppositeSide()),
                          board_copy.sideToMove())) {
                      ++dups;
                      start = maybe;
                   }
                }
             }
          }
       }
    }
    if (dups == 1 || have_start) {
       if (start == InvalidSquare || board[start] == EmptyPiece)
          return NullMove;
       else
          return CreateMove(board, start, dest, promotion);
    }
    else                                           // ambiguous move
       return NullMove;
}