Exemple #1
0
/* NOTE: despite what you would expect, 'file_name' is actually a path.
 * With windoze style backlashes, ofc.
 */
static struct efi_file_handle *file_open(struct file_system *fs,
		struct file_handle *parent, s16 *file_name, u64 mode)
{
	struct file_handle *fh;
	char f0[MAX_UTF8_PER_UTF16] = {0};
	int plen = 0;
	int flen = 0;

	if (file_name) {
		utf16_to_utf8((u8 *)f0, (u16 *)file_name, 1);
		flen = utf16_strlen((u16 *)file_name);
	}

	/* we could have a parent, but also an absolute path: */
	if (f0[0] == '\\') {
		plen = 0;
	} else if (parent) {
		plen = strlen(parent->path) + 1;
	}

	/* +2 is for null and '/' */
	fh = calloc(1, sizeof(*fh) + plen + (flen * MAX_UTF8_PER_UTF16) + 2);

	fh->base = efi_file_handle_protocol;
	fh->fs = fs;

	if (parent) {
		char *p = fh->path;

		if (plen > 0) {
			strcpy(p, parent->path);
			p += plen - 1;
			*p++ = '/';
		}

		utf16_to_utf8((u8 *)p, (u16 *)file_name, flen);

		if (sanitize_path(fh->path))
			goto error;

		/* check if file exists: */
		if (set_blk_dev(fh))
			goto error;

		if (!((mode & EFI_FILE_MODE_CREATE) || fs_exists(fh->path)))
			goto error;

		/* figure out if file is a directory: */
		fh->isdir = is_dir(fh);
	} else {
		fh->isdir = 1;
		strcpy(fh->path, "");
	}

	return &fh->base;

error:
	free(fh);
	return NULL;
}
Exemple #2
0
// Use a simpler approach to make sure that things go right for libretro.
std::string MDFN_MakeFName(MakeFName_Type type, int id1, const char *cd1)
{
   char slash;
#ifdef _WIN32
   slash = '\\';
#else
   slash = '/';
#endif
   std::string ret;
   switch (type)
   {
      case MDFNMKF_SAV:
         ret = retro_save_directory +slash + retro_base_name +
            std::string(".") +
#ifndef _XBOX
	    md5_context::asciistr(MDFNGameInfo->MD5, 0) + std::string(".") +
#endif
            std::string(cd1);
         break;
      case MDFNMKF_FIRMWARE:
         ret = retro_base_directory + slash + std::string(cd1);
#ifdef _WIN32
   sanitize_path(ret); // Because Windows path handling is mongoloid.
#endif
         break;
      default:	  
         break;
   }

   if (log_cb)
      log_cb(RETRO_LOG_INFO, "MDFN_MakeFName: %s\n", ret.c_str());
   return ret;
}
Exemple #3
0
/* Creates a NTFS by executing mkfs.ntfs. This does not need root privileges */
int create_ntfs_filesystem(char *prefix, char *filename, char *partname, int cluster_size) {
  /*  char *arg[20];*/
  char *path;
  int i,result=0;
  char cluster_string[8];
  pid_t pid;
  
  if (setuid(getuid()) == -1) {
    perror(PNAME);
    exit(1);
  }

  if (filename == NULL) {
    fprintf(stderr, "filename unset\n");
    exit(1);
  }
  if (partname == NULL) {
    fprintf(stderr, "partition name unset\n");
    exit(1);
  }
  path = malloc(sizeof(char)*(strlen(prefix)+strlen(filename)+1));
  if (path == NULL) {
    perror(PNAME);
    exit(1);
  }
  strcpy(path, prefix);
  strcat(path, filename);
  sanitize_path(path);

  sprintf(cluster_string, "%d", cluster_size);
  
  char *arg[] = {MKFS_NTFS,"-L", partname, "-c", cluster_string, "-s", "512", "-p", "0", "-S", "0", "-H", "0", "-F", "-f", "-q", path, NULL};

  pid = fork();
  if (pid == -1) {
    perror(PNAME);
    exit(1);
  }
  if (pid == 0) {
    /* 
       mkfs complains about file not being a block device.
       We don't want that. 
    */
    close(STDERR_FILENO);
    close(STDOUT_FILENO);
    if (execv(MKFS_NTFS, arg) == -1) {
      perror(PNAME);
      exit(1);
    }
    /* This is never reached */
  }
  else {
    wait (&result);
    return (result);
  }	 
  /* This is never reached */
  return (-1);
}  
Exemple #4
0
void handle_http_get_request(http_client* client, http_request* request)
{
	if ((!client) || (!request)) {
		err_log("handle_http_get_request: got null pointer in client or request");
		return;
	}

	char* sanitized_path = sanitize_path(request->path+1); /* skip '/' at beginning of path ***FIXME*** */
	if (!sanitized_path) {
		err_log("handle_http_get_request: illegal path: %s", request->path);
	}

	if (0 == strcmp(sanitized_path, MAGIC_FILE_NAME)) {
		if (!canbus_modify_message(request))
			err_log("handle_http_get_request: canbus_modify_message() failed");
		char response_header[] = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
		Send(client->sock, response_header, strlen(response_header));
#ifdef SPRITZE
		canbus_send_message();
#endif
		return;
	}

	/* ***FIXME*** use absolute path, webserver root directory, etc. */
	FILE* f = fopen(sanitized_path, "r");
	if (!f) {
		char msg[] = "HTTP/1.1 404 File Not Found\r\n\r\n"
			     "<html><title>404</title><body><h1>"
			     "404 File Not Found</h1></body></html>\r\n";
		Send(client->sock, msg, strlen(msg));
		return;
	}

	struct stat file_info;
	if (-1 == (fstat(fileno(f), &file_info))) {
		fclose(f);
		err_sys("handle_http_get_request: fstat() failed");
		return;
	}

	char response_header[MAX_HTTP_RESPONSE_LENGTH+1] = "HTTP/1.1 200 OK\r\nConnection: close\r\n";
	char length[255];

	snprintf(length, sizeof(length), "Content-Length: %d\r\n", (int)file_info.st_size);
	strncat(response_header, length, sizeof(response_header)-strlen(response_header)-1);
	strncat(response_header, "Content-Type: application/xml\r\n\r\n",
		sizeof(response_header)-strlen(response_header)-1);
	response_header[MAX_HTTP_RESPONSE_LENGTH] = '\0';

	Send(client->sock, response_header, strlen(response_header));
	send_file(client, request, f);
	fclose(f);		/* checking return value is pointless, since if fclose() fails, */
				/* we can't do anything useful about it. */
}
Exemple #5
0
void create_file(char *prefix, char *filename, long size, int contents) {
  long i;
  char *path,wchar,*fbuf;
  int fd;

  /* This does not need root privileges */
  if (setuid(getuid()) == -1) {
    perror(PNAME);
    exit(1);
  }
  if (filename == NULL) {
    fprintf(stderr, "filename unset\n");
    exit(1);
  }

  path = malloc(sizeof(char)*(strlen(prefix)+strlen(filename)+1));
  if (path == NULL) {
    perror(PNAME);
    exit(1);
  }
  strcpy(path, prefix);
  strcat(path, filename);
  sanitize_path(path);

  fd = open(path,O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR| S_IRGRP|S_IWGRP|S_IROTH);


  /* Refuse to overwrite an existing file */

  if (fd == -1) {
    fprintf(stderr,"File exists\n");
    exit(1);
  }
  fbuf = malloc(sizeof(char)*(size+1));
  if (fbuf == NULL) {
    perror(PNAME);
    exit(1);
  }
  wchar = 0;
  for (i=0;i<size;i++) {
    if (contents == C_RANDOM) {
      wchar = rand() % 256;
    }
    fbuf[i] = wchar;

  }

  if (write(fd,fbuf,(size_t) size) == -1) {
    perror(PNAME);
    exit(1);
  }
  free (fbuf);
  close(fd);
}
Exemple #6
0
int td_sanitize_lua_path(lua_State *L)
{
	char buffer[512];
	size_t path_len;
	const char *path = luaL_checklstring(L, 1, &path_len);
	if (path_len >= sizeof(buffer))
		return luaL_error(L, "path too long; %d > %d", (int) path_len, (int) sizeof(buffer));
	strcpy(buffer, path);
	sanitize_path(buffer, sizeof(buffer), path_len);
	lua_pushstring(L, buffer);
	return 1;
}
Exemple #7
0
void interactive_categorize() {
  char *s;
  FILE *input;

  if( (s = get_input_line("Sort current mailbox by category: ", "")) ) { 

    if( s[0] != '\0' ) {
      cat[1].fullfilename = sanitize_path(s, extn);
      if( load_category(&cat[1]) && 
	  (input = fopen(emails.filename, "rb")) ) {

	sanitize_model_options(&m_options, &m_cp, &cat[1]);
	ephemeral_message("Please wait, recalculating scores");
	/* loaded category successfully, now free old resources */
	free_category(&cat[0]);
	memcpy(&cat[0], &cat[1], sizeof(category_t));
      
	free_emails();
	init_emails();
	
	read_mbox_and_sort_list(input);
      
	if( u_options & (1<<U_OPTION_REVSORT) ) {
	  reverse_sort();
	  recalculate_limited();
	}
      
	fclose(input);
      } else {
	ephemeral_message("Sorry, the category could not be loaded");
      }
    }

    free(s);
  }
}
Exemple #8
0
td_file *
td_engine_get_file(td_engine *engine, const char *input_path, td_get_file_mode mode)
{
	unsigned int hash;
	int slot;
	td_file *chain;
	td_file *f;
	int path_len;
	char path[1024];
	const char *out_path;
	size_t input_path_len = strlen(input_path);

	if (input_path_len >= sizeof(path))
		td_croak("path too long: %s", input_path);

	if (TD_COPY_STRING == mode)
	{
		if (isabspath(input_path))
		{
			strcpy(path, input_path);
		}
		else
		{
			snprintf(path, sizeof path, "%s%s", cwd, input_path);
		}

		sanitize_path(path, sizeof(path), input_path_len);
		hash = (unsigned int) djb2_hash(path);
		out_path = path;
	}
	else
	{
		hash = (unsigned int) djb2_hash(input_path);
		out_path = input_path;
	}

	td_mutex_lock_or_die(engine->lock);

	slot = (int) (hash % engine->file_hash_size);
	chain = engine->file_hash[slot];

	while (chain)
	{
		if (chain->hash == hash && 0 == strcmp(out_path, chain->path))
		{
			td_mutex_unlock_or_die(engine->lock);
			return chain;
		}

		chain = chain->bucket_next;
	}

	++engine->stats.file_count;
	f = td_page_alloc(&engine->alloc, sizeof(td_file));
	memset(f, 0, sizeof(td_file));

	f->path_len = path_len = (int) strlen(out_path);
	if (TD_COPY_STRING == mode)
		f->path = td_page_strdup(&engine->alloc, out_path, path_len);
	else
		f->path = out_path;
	f->hash = hash;
	f->name = find_basename(f->path, path_len);
	f->bucket_next = engine->file_hash[slot];
	f->signer = engine->default_signer;
	f->stat_dirty = 1;
	f->signature_dirty = 1;
	f->frozen_relstring_index = ~(0u);
	engine->file_hash[slot] = f;
	td_mutex_unlock_or_die(engine->lock);
	return f;
}
Exemple #9
0
 void create_socket(std::string file)
 {
     file = sanitize_path(file);
     python_run(elib::fmt("create_socket('%s')", file));
 }
static int rsync_module(int fd, int i)
{
	int argc=0;
	char *argv[MAX_ARGS];
	char **argp;
	char line[MAXPATHLEN];
	uid_t uid = (uid_t)-2;
	gid_t gid = (gid_t)-2;
	char *p;
	char *addr = client_addr(fd);
	char *host = client_name(fd);
	char *name = lp_name(i);
	int use_chroot = lp_use_chroot(i);
	int start_glob=0;
	int ret;
	char *request=NULL;
	extern int am_sender;
	extern int remote_version;
	extern int am_root;

	if (!allow_access(addr, host, lp_hosts_allow(i), lp_hosts_deny(i))) {
		rprintf(FERROR,"rsync denied on module %s from %s (%s)\n",
			name, client_name(fd), client_addr(fd));
		io_printf(fd,"@ERROR: access denied to %s from %s (%s)\n",
			  name, client_name(fd), client_addr(fd));
		return -1;
	}

	if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
		if (errno) {
			rprintf(FERROR,"failed to open lock file %s : %s\n",
				lp_lock_file(i), strerror(errno));
			io_printf(fd,"@ERROR: failed to open lock file %s : %s\n",
				  lp_lock_file(i), strerror(errno));
		} else {
			rprintf(FERROR,"max connections (%d) reached\n",
				lp_max_connections(i));
			io_printf(fd,"@ERROR: max connections (%d) reached - try again later\n", lp_max_connections(i));
		}
		return -1;
	}

	
	auth_user = auth_server(fd, i, addr, "@RSYNCD: AUTHREQD ");

	if (!auth_user) {
		rprintf(FERROR,"auth failed on module %s from %s (%s)\n",
			name, client_name(fd), client_addr(fd));
		io_printf(fd,"@ERROR: auth failed on module %s\n",name);
		return -1;		
	}

	module_id = i;

	if (lp_read_only(i))
		read_only = 1;

	am_root = (getuid() == 0);

	if (am_root) {
		p = lp_uid(i);
		if (!name_to_uid(p, &uid)) {
			if (!isdigit(*p)) {
				rprintf(FERROR,"Invalid uid %s\n", p);
				io_printf(fd,"@ERROR: invalid uid\n");
				return -1;
			} 
			uid = atoi(p);
		}

		p = lp_gid(i);
		if (!name_to_gid(p, &gid)) {
			if (!isdigit(*p)) {
				rprintf(FERROR,"Invalid gid %s\n", p);
				io_printf(fd,"@ERROR: invalid gid\n");
				return -1;
			} 
			gid = atoi(p);
		}
	}

	p = lp_include_from(i);
	add_exclude_file(p, 1, 1);

	p = lp_include(i);
	add_include_line(p);

	p = lp_exclude_from(i);
	add_exclude_file(p, 1, 0);

	p = lp_exclude(i);
	add_exclude_line(p);

	log_open();

	if (use_chroot) {
		if (chroot(lp_path(i))) {
			rprintf(FERROR,"chroot %s failed\n", lp_path(i));
			io_printf(fd,"@ERROR: chroot failed\n");
			return -1;
		}

		if (!push_dir("/", 0)) {
			rprintf(FERROR,"chdir %s failed\n", lp_path(i));
			io_printf(fd,"@ERROR: chdir failed\n");
			return -1;
		}

	} else {
		if (!push_dir(lp_path(i), 0)) {
			rprintf(FERROR,"chdir %s failed\n", lp_path(i));
			io_printf(fd,"@ERROR: chdir failed\n");
			return -1;
		}
	}

	if (am_root) {
		if (setgid(gid)) {
			rprintf(FERROR,"setgid %d failed\n", gid);
			io_printf(fd,"@ERROR: setgid failed\n");
			return -1;
		}

		if (setuid(uid)) {
			rprintf(FERROR,"setuid %d failed\n", uid);
			io_printf(fd,"@ERROR: setuid failed\n");
			return -1;
		}

		am_root = (getuid() == 0);
	}

	io_printf(fd,"@RSYNCD: OK\n");

	argv[argc++] = "rsyncd";

	while (1) {
		if (!read_line(fd, line, sizeof(line)-1)) {
			return -1;
		}

		if (!*line) break;

		p = line;

		argv[argc] = strdup(p);
		if (!argv[argc]) {
			return -1;
		}

		if (start_glob) {
			if (start_glob == 1) {
				request = strdup(p);
				start_glob++;
			}
			glob_expand(name, argv, &argc, MAX_ARGS, !use_chroot);
		} else {
			argc++;
		}

		if (strcmp(line,".") == 0) {
			start_glob = 1;
		}

		if (argc == MAX_ARGS) {
			return -1;
		}
	}

	if (!use_chroot) {
		/*
		 * Note that this is applied to all parameters, whether or not
		 *    they are filenames, but no other legal parameters contain
		 *    the forms that need to be sanitized so it doesn't hurt;
		 *    it is not known at this point which parameters are files
		 *    and which aren't.
		 */
		for (i = 1; i < argc; i++) {
			sanitize_path(argv[i]);
		}
	}

	ret = parse_arguments(argc, argv, 0);

	if (request) {
		if (*auth_user) {
			rprintf(FINFO,"rsync %s %s from %s@%s (%s)\n",
				am_sender?"on":"to",
				request, auth_user, host, addr);
		} else {
			rprintf(FINFO,"rsync %s %s from %s (%s)\n",
				am_sender?"on":"to",
				request, host, addr);
		}
		free(request);
	}

#if !TRIDGE
	/* don't allow the logs to be flooded too fast */
	if (verbose > 1) verbose = 1;
#endif

	argc -= optind;
	argp = argv + optind;
	optind = 0;

	if (remote_version > 17 && am_sender)
		io_start_multiplex_out(fd);

	if (!ret) {
		option_error();
	}

	if (lp_timeout(i)) {
		extern int io_timeout;
		io_timeout = lp_timeout(i);
	}

	start_server(fd, fd, argc, argp);

	return 0;
}
Exemple #11
0
int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
		       char *buf, int *len_ptr)
{
	int len, iflags = 0;
	struct file_list *flist;
	uchar fnamecmp_type = FNAMECMP_FNAME;
	int ndx;

  read_loop:
	while (1) {
		ndx = read_ndx(f_in);

		if (ndx >= 0)
			break;
		if (ndx == NDX_DONE)
			return ndx;
		if (ndx == NDX_DEL_STATS) {
			read_del_stats(f_in);
			if (am_sender && am_server)
				write_del_stats(f_out);
			continue;
		}
		if (!inc_recurse || am_sender) {
			int last;
			if (first_flist)
				last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
			else
				last = -1;
			rprintf(FERROR,
				"Invalid file index: %d (%d - %d) [%s]\n",
				ndx, NDX_DONE, last, who_am_i());
			exit_cleanup(RERR_PROTOCOL);
		}
		if (ndx == NDX_FLIST_EOF) {
			flist_eof = 1;
			if (DEBUG_GTE(FLIST, 3))
				rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
			write_int(f_out, NDX_FLIST_EOF);
			continue;
		}
		ndx = NDX_FLIST_OFFSET - ndx;
		if (ndx < 0 || ndx >= dir_flist->used) {
			ndx = NDX_FLIST_OFFSET - ndx;
			rprintf(FERROR,
				"Invalid dir index: %d (%d - %d) [%s]\n",
				ndx, NDX_FLIST_OFFSET,
				NDX_FLIST_OFFSET - dir_flist->used + 1,
				who_am_i());
			exit_cleanup(RERR_PROTOCOL);
		}

		if (DEBUG_GTE(FLIST, 2)) {
			rprintf(FINFO, "[%s] receiving flist for dir %d\n",
				who_am_i(), ndx);
		}
		/* Send all the data we read for this flist to the generator. */
		start_flist_forward(ndx);
		flist = recv_file_list(f_in, ndx);
		flist->parent_ndx = ndx;
		stop_flist_forward();
	}

	iflags = protocol_version >= 29 ? read_shortint(f_in)
		   : ITEM_TRANSFER | ITEM_MISSING_DATA;

	/* Support the protocol-29 keep-alive style. */
	if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
		if (am_sender)
			maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
		goto read_loop;
	}

	flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
	if (flist != cur_flist) {
		cur_flist = flist;
		if (am_sender) {
			file_old_total = cur_flist->used;
			for (flist = first_flist; flist != cur_flist; flist = flist->next)
				file_old_total += flist->used;
		}
	}

	if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
		fnamecmp_type = read_byte(f_in);
	*type_ptr = fnamecmp_type;

	if (iflags & ITEM_XNAME_FOLLOWS) {
		if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
			exit_cleanup(RERR_PROTOCOL);

		if (sanitize_paths) {
			sanitize_path(buf, buf, "", 0, SP_DEFAULT);
			len = strlen(buf);
		}
	} else {
		*buf = '\0';
		len = -1;
	}
	*len_ptr = len;

	if (iflags & ITEM_TRANSFER) {
		int i = ndx - cur_flist->ndx_start;
		if (i < 0 || !S_ISREG(cur_flist->files[i]->mode)) {
			rprintf(FERROR,
				"received request to transfer non-regular file: %d [%s]\n",
				ndx, who_am_i());
			exit_cleanup(RERR_PROTOCOL);
		}
	}

	*iflag_ptr = iflags;
	return ndx;
}
Exemple #12
0
static void handle_conn_write(struct conn *p_conn, struct pollfd *p_pollfd) {
  int done = 0;
  ssize_t send_size;

  /* Log some debug info. */
  log_debug(NULL, "Writing connection %lu/socket %d (assigned pollfd %lu)",
      (unsigned long) p_conn->conn_idx,
      p_conn->sock,
      (unsigned long) p_conn->pollfd_idx);

  if (p_conn->stage == STAGE_RESPONSE_START) {
    char *selector = p_conn->buf, *raw_path = NULL, *log_msg;

    if (asprintf(&raw_path, "%s/%s", g_config.srv_path, selector) < 0) {
      log_pwarn(p_conn->addr_str, "Couldn't allocate resource path");
      done = 1;
      goto cleanup_response_start;
    }

    errno = 0;
    if (sanitize_path(raw_path, &p_conn->path)) {
      if (errno) {
        switch (errno) {
          case EACCES:
          case EIO:
          case ELOOP:
          case ENAMETOOLONG:
          case ENOENT:
          case ENOTDIR:
            log_msg = "Denied request: %s [%s] - %s";
            p_conn->item_type = ITEM_TYPE_ERR;
            break;

          default:
            log_pwarn(p_conn->addr_str, "Couldn't sanitize resource path");
            done = 1;
            goto cleanup_response_start;
        }
      } else {
        log_msg = "Denied request: %s [%s] - Outside service path";
        p_conn->item_type = ITEM_TYPE_ERR;
      }
    } else {
      log_msg = "Allowed request: %s [%s]";
    }

    log_info(p_conn->addr_str, log_msg, selector,
        p_conn->path ? p_conn->path : raw_path, strerror(errno));

    if (!p_conn->item_type
        && !(p_conn->item_type = get_item_type(p_conn->path))) {
      log_pwarn(p_conn->addr_str, "Could not determine item type");
      done = 1;
      goto cleanup_response_start;
    }

    switch (p_conn->item_type) {
    case ITEM_TYPE_ERR:
      new_fail_response(p_conn);
      break;

    case ITEM_TYPE_DIR:
      new_menu_response(p_conn);
      break;

    default:
      new_file_response(p_conn);
    }

    if (p_conn->init_response(p_conn)) {
      done = 1;
      goto cleanup_response_start;
    }

    p_conn->stage = STAGE_RESPONSE_BODY;

  cleanup_response_start:
    free(raw_path);

    if (done) {
      goto cleanup;
    }
  }

  if (!p_conn->data_size) {
    p_conn->buf_next = p_conn->buf + p_conn->state_size;

    if (p_conn->buffer_response(p_conn)) {
      done = 1;
      goto cleanup;
    }
  }

  if (!p_conn->data_size) {
    done = 1;
    goto cleanup;
  }

  if ((send_size
          = r_write(p_conn->sock, p_conn->buf_next, p_conn->data_size))
      == -1) {
    if (errno != EAGAIN && errno != EWOULDBLOCK) {
      done = 1;
    }

    goto cleanup;
  }

  p_conn->buf_next += send_size;
  p_conn->data_size -= send_size;

cleanup:
  if (done) {
    handle_conn_delete(p_conn, p_pollfd);
  }
}
Exemple #13
0
 void create_hardlink(std::string source, std::string to)
 {
     source = sanitize_path(source);
     to = sanitize_path(to);
     python_run(elib::fmt("create_hardlink('%s', '%s')", source, to));
 }
Exemple #14
0
main (int argc, char **argv) {
  char *params[10], *lodevice;
  char *prefix, *fname, *mountpoint;
  pid_t pid, cluster_size=0;
  int status,opt=0,q=0;
  long size=0;

#ifdef PATH  
  if (strlen(PATH) > MAX_PATH_LENGTH) {
    fprintf(stderr, "too long PATH\n");
    exit(1);
  }
  prefix = malloc(sizeof(char)*strlen(PATH)+1);
  if (prefix == NULL) {
    perror(PNAME);
    exit(1);
  }
  strcpy (prefix,PATH);
#else
#error "must define PATH"
#endif

#ifdef MOUNTPOINT
  if (strlen(MOUNTPOINT) > MAX_PATH_LENGTH) {
    fprintf(stderr, "too long MOUNTPOINT\n");
    exit(1);
  }
  mountpoint = malloc(sizeof(char)*strlen(MOUNTPOINT)+1);
  if (mountpoint == NULL) {
    perror(PNAME);
    exit(1);
  }
  strcpy (mountpoint,MOUNTPOINT);
  sanitize_path(mountpoint);
#else
#error "must define MOUNTPOINT"
#endif

  if (argc < 2) {
    fprintf(stderr,"Usage: %s [create fstype size cluster_size name [clean | random] filename | attach fstype filename | detach]\n", PNAME);
    exit(1);
  }

  if (strcmp(argv[1], "create") == 0) {
    if (argc < 2) {
      fprintf(stderr,"Usage: %s create ntfs|FAT16 ...\n", PNAME);
      exit(1);
    }
    if (strcmp(argv[2], "ntfs") == 0) {
      if (argc != 8) {
	fprintf(stderr,"Usage: %s create fstype size cluster_size name [clean | random] filename\n", PNAME);
	exit(1);
      }
      /* freopen("/dev/null","w",stderr);*/
      if (strlen(argv[3]) > 12) {
	fprintf(stderr,"Too long size parameter\n");
	exit(1);
      }
      size = calculate_size(argv[3]);
      if (strlen(argv[7]) > MAX_PATH_LENGTH) {
	fprintf(stderr, "Too long parameter %s\n", argv[7]);
	exit(1);
      }
      fname = malloc(sizeof(char)*strlen(argv[7])+1);
      if (fname == NULL) {
	perror(PNAME);
	exit(1);
      }
      strcpy(fname, argv[7]);
      if ((atoi(argv[4]) < 1 || atoi (argv[4]) > 32) || atoi(argv[4]) & 1) {
	fprintf(stderr,"Cluster size must be a multiple of 2 and max 32\n");
	exit(1);
      }
      cluster_size = atoi(argv[4])*512;

      /* Generally we could be more allowing here but use the same routine
	 for reasons of pure laziness. 
	 Technically only white space, ?, *, " and ' should be really 
	 frowned upon here 
      */
      sanitize_path(argv[5]);
      if (strlen(argv[5]) > 20) {
	fprintf(stderr, "too long parameter %s", argv[5]);
	exit(1);
      }
      if (strcmp(argv[6], "random") == 0) {
	create_file(prefix, fname, size, C_RANDOM);
      } 
      else {
	create_file(prefix, fname, size, C_ZERO);
      }
      create_ntfs_filesystem(prefix, fname, argv[5], cluster_size);
      exit(0);
    }
    if ((strcmp(argv[2], "FAT16") == 0) || (strcmp(argv[2],"FAT32") == 0) || (strcmp(argv[2], "FAT12") == 0) || 
	(strcmp(argv[2], "GENERICFAT") == 0)) {
      if (argc != 9) {
	fprintf(stderr,"Usage: %s create FAT16|FAT12|FAT32 size cluster_size sector_size name [clean | random] filename\n", PNAME);
	exit(1);
      }
      /* freopen("/dev/null","w",stderr);*/
      if (strlen(argv[3]) > 12) {
	fprintf(stderr,"Too long size parameter\n");
	exit(1);
      }
      size = calculate_size(argv[3]);
      if (strlen(argv[8]) > MAX_PATH_LENGTH) {
	fprintf(stderr, "Too long parameter %s\n", argv[8]);
	exit(1);
      }
      fname = malloc(sizeof(char)*strlen(argv[7])+1);
      if (fname == NULL) {
	perror(PNAME);
	exit(1);
      }
      strcpy(fname, argv[8]);
      if ((atoi(argv[4]) < 1 || atoi (argv[4]) > 32) || atoi(argv[4]) & 1) {
	fprintf(stderr,"Cluster size must be a multiple of 2 and max 32\n");
	exit(1);
      }
      cluster_size = atoi(argv[4])*512;
      if ((atoi(argv[5]) < 512 || atoi (argv[5]) > 32768) || (atoi(argv[5]) & (atoi(argv[5])-1))) {
	fprintf(stderr,"Sector size must be a multiple of 512, max 32768 and a power of two\n");
	exit(1);
      }
      /* Generally we could be more allowing here but use the same routine
	 for reasons of pure laziness. 
	 Technically only white space, ?, *, " and ' should be really 
	 frowned upon here 
      */
      sanitize_path(argv[6]);
      if (strlen(argv[6]) > 11) {
	fprintf(stderr, "too long parameter %s (max 11 chars)\n", argv[6]);
	exit(1);
      }

      if (strcmp(argv[7], "random") == 0) {
	create_file(prefix, fname, size, C_RANDOM);
      } 
      else {
	create_file(prefix, fname, size, C_ZERO);
      }

      create_fat_filesystem(prefix, argv[2], fname, argv[6], atoi(argv[5]),argv[4]);
      exit(0);
    }
    else {
      fprintf(stderr, "Unknown file system type %s\n", argv[2]);
      exit(1);
    }
  }    


  
  /* Attach */
  if (strcmp(argv[1], "attach") == 0) {
    if (argc != 4) {
      fprintf(stderr,"Usage: %s attach fstype filename\n", PNAME);
      exit(1);
    }
    if (strlen(argv[3]) > MAX_PATH_LENGTH) {
      fprintf(stderr, "Too long parameter %s\n", argv[3]);
      exit(1);
    }
    fname = malloc(sizeof(char)*strlen(argv[3])+1);
    if (fname == NULL) {
      perror(PNAME);
      exit(1);
    }
    strcpy(fname, argv[3]);
    lodevice = attach_file(prefix,fname);
    if (lodevice) {
      if (strcmp(argv[2],"ntfs") == 0) {
	q = mount_ntfs_filesystem(lodevice);
	if (q != 0) 
	  detach_device(lodevice);
	exit(q);
      }
      if (strncmp(argv[2], "FAT",3 ) == 0) {
	q = mount_fat_filesystem(lodevice);
	if (q != 0)
	  detach_device(lodevice);
	exit(q);
      }
      else {
	fprintf(stderr, "unknown file system type %s\n", argv[2]);
	detach_device(lodevice);
	exit(1);
      }
    }
    else
      fprintf (stderr, "Cannot find loopback device\n");
    exit(0);
  }
  
  /* detach */
  if (strcmp(argv[1], "detach") == 0) {
    freopen("/dev/null","w",stderr);
    exit(detach_image());
  }
  fprintf(stderr,"Usage: %s [create fstype size cluster_size name [clean | random] filename | attach fstype filename | detach]\n", PNAME);  
  exit(1);
}
Exemple #15
0
 void create_file(std::string filename, std::size_t size = 0)
 {
     filename = sanitize_path(filename);
     python_run(elib::fmt("create_file('%s', %u)", filename, size));
 }
Exemple #16
0
/* Creates FAT filesystem */
int create_fat_filesystem(char *prefix, char *fattype, char *filename, char *partname, int sector_size, char *cluster_size) {
  char *path, *output, fatso[3];
  int i, result=0, ipipe[2];
  char sector_string[8];
  char *arg[11];
  pid_t pid;

  if (setuid(getuid()) == -1) {
    perror(PNAME);
    exit(1);
  }

  if (filename == NULL) {
    fprintf(stderr, "filename unset\n");
    exit(1);
  }
  if (partname == NULL) {
    fprintf(stderr, "partition name unset\n");
    exit(1);
  }
  path = malloc(sizeof(char)*(strlen(prefix)+strlen(filename)+1));
  if (path == NULL) {
    perror(PNAME);
    exit(1);
  }
  strcpy(path, prefix);
  strcat(path, filename);
  sanitize_path(path);

  sprintf(sector_string, "%d", sector_size);
  if (strcmp(fattype, "GENERICFAT") == 0) {
    /* char *arg = {MKFS_FAT, "-S", sector_string, "-s", cluster_size, "-n", partname, path, NULL}; */
    arg[0] = MKFS_FAT;
    arg[1] = "-S";
    arg[2] = sector_string;
    arg[3] = "-n";
    arg[4] = partname;
    arg[5] = path;
    arg[6] = NULL;
  }
  else {
    strcpy(fatso, fattype+3);
    /*    arg = {MKFS_FAT, "-F", fatso, "-S", sector_string, "-s", cluster_size, "-n", partname, path, NULL}; */
    arg[0] = MKFS_FAT;
    arg[1] = "-S";
    arg[2] = sector_string;
    arg[3] = "-s";
    arg[4] = cluster_size;
    arg[5] = "-n";
    arg[6] = partname;
    arg[7] = "-F";
    arg[8] = fatso;
    arg[9] = path;
    arg[10] = NULL;
  }
  if (pipe(ipipe)) {
    perror(PNAME);
    exit(1);
  }
  pid = fork();
  if (pid == -1) {
    perror(PNAME);
    exit(1);
  }
  if (pid == 0) {
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    dup2(ipipe[1], STDOUT_FILENO);
    dup2(ipipe[1], STDERR_FILENO);
    close(ipipe[0]);
    close(ipipe[1]);

    if (execv(MKFS_FAT, arg) == -1) {
      perror(PNAME);
      exit(1);
    }
    /* This is never reached */
    return (1);
  }
  else {
    close(ipipe[1]);
    output = malloc(4096*sizeof(char));
    if (output == NULL) {
      perror(PNAME);
      exit(1);
    }
    output[read(ipipe[0],output,4095)] = 0;
    wait (&result);
    if (strstr(output, "WARNING:") != NULL) {
      fprintf(stderr, "wrong sector/cluster combination - not able to create FAT\n");
      exit(1);
    }
    if (strstr(output, "Too many clusters") != NULL) {
      fprintf(stderr, "Too many clusters for FAT file system\n");
      exit(1);
    }
    exit(0);
  }
  /* never reached */
  fprintf(stderr, "something is wrong \n");
  exit(1);
}
Exemple #17
0
char *attach_file(char *prefix, char *command) {
  int i,result=42;
  char *path;
  pid_t   pid;
  char  *arg[10];
  int ipipe[2];
  char *loopback;
  struct stat statbuf;

  if (!is_dir_empty(MOUNTPOINT)) {
    fprintf(stderr,"Mount point not empty\n");
    exit(1);
  }
  path = malloc(sizeof(char)*(strlen(prefix)+strlen(command)+1));
  if (path == NULL) {
    perror(PNAME);
    exit(1);
  }
  strcpy(path, prefix);
  strcat(path, command);
  sanitize_path(path);

  if (lstat (path, &statbuf) == -1) {
    perror(PNAME);
    exit(1);
  }
  if (statbuf.st_nlink != 1) {
    fprintf(stderr, "File has hard links to it, cannot proceed.\n");
    exit(1);
  }
  if ((statbuf.st_mode & S_IFMT) != S_IFREG) {
    fprintf(stderr, "file is not a regular file, go away\n");
    exit(1);
  }



  /* A kludge to redirect child stdout back to parent to find a loopback device */
  if (pipe(ipipe)) {
    perror(PNAME);
    exit(1);
  }

  /* Fork to run losetup -f to get a free loopback interface */
  pid = fork();
  if (pid == -1) {
    perror(PNAME);
    exit(1);
  }
  if (pid == 0) {
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    dup2(ipipe[1], STDOUT_FILENO);
    close(ipipe[0]);
    close(ipipe[1]);

    arg[0] = LOSETUP;
    arg[1] = "-f";
    arg[2] = NULL;
    if (execv(LOSETUP, arg) == -1) {
      perror(PNAME);
      exit(1);
    }
    /* This is never reached */
    return NULL;
  }
  else {
    close(ipipe[1]);
    loopback = malloc(256*sizeof(char));
    if (loopback == NULL) {
      perror(PNAME);
      exit(1);
    }
    loopback[read(ipipe[0],loopback,256)] = 0;
    if (strlen(loopback) < 5) {
      fprintf(stderr, "no loopback device found\n");
      wait(&result);
      close(ipipe[0]);
      exit(1);
    }
    /* Get a free loopback device to loopback */
    loopback[strlen(loopback)-1] = 0;
    wait(&result);
    close(ipipe[0]);
    if (result != 0) {
      fprintf(stderr, "this should not happen, losetup -f did not return a proper value\n");
      exit(result);
    }
    /* Attach the loopback device. Examine return value as not a single state operation */
    arg[0] = LOSETUP;
    arg[1] = loopback;
    arg[2] = path;
    arg[3] = NULL;

    /* Fork to exec losetup /dev/loopx pathname */
    pid = fork();
    if (pid == -1) {
      perror(PNAME);
      exit(1);
    }
    if (pid == 0) {
      if (execv(LOSETUP, arg) == -1) {
	perror(PNAME);
	exit(1);
      }
      /* This is never reached */
      return NULL;
    }
    else {
      wait (&result);
      if (result == 0) 
	return loopback;
      else {
	free(loopback);
	return NULL;
      }
    }
  }
}
static char *
impl_build_dest_uri (RBRemovableMediaSource *source,
		     RhythmDBEntry *entry,
		     const char *mimetype,
		     const char *extension)
{
	RBGenericPlayerSourcePrivate *priv = GENERIC_PLAYER_SOURCE_GET_PRIVATE (source);
	char *artist, *album, *title;
	gulong track_number, disc_number;
	const char *folders;
	char **audio_folders;
	char *mount_path;
	char *number;
	char *file = NULL;
	char *path;
	char *ext;

	rb_debug ("building dest uri for entry at %s", rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_LOCATION));

	if (extension != NULL) {
		ext = g_strconcat (".", extension, NULL);
	} else {
		ext = g_strdup ("");
	}

	artist = sanitize_path (rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_ARTIST));
	album = sanitize_path (rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_ALBUM));
	title = sanitize_path (rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_TITLE));

	/* we really do need to fix this so untagged entries actually have NULL rather than
	 * a translated string.
	 */
	if (strcmp (artist, _("Unknown")) == 0 && strcmp (album, _("Unknown")) == 0 &&
	    g_str_has_suffix (rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_LOCATION), title)) {
		/* file isn't tagged, so just use the filename as-is, replacing the extension */
		char *p;

		p = g_utf8_strrchr (title, -1, '.');
		if (p != NULL) {
			*p = '\0';
		}
		file = g_strdup_printf ("%s%s", title, ext);
	}

	if (file == NULL) {
		int folder_depth;

		track_number = rhythmdb_entry_get_ulong (entry, RHYTHMDB_PROP_TRACK_NUMBER);
		disc_number = rhythmdb_entry_get_ulong (entry, RHYTHMDB_PROP_DISC_NUMBER);
		if (disc_number > 0)
			number = g_strdup_printf ("%.02u.%.02u", (guint)disc_number, (guint)track_number);
		else
			number = g_strdup_printf ("%.02u", (guint)track_number);

		g_object_get (priv->device_info, "folder-depth", &folder_depth, NULL);
		switch (folder_depth) {
		case 0:
			/* artist - album - number - title */
			file = g_strdup_printf ("%s - %s - %s - %s%s",
						artist, album, number, title, ext);
			break;

		case 1:
			/* artist - album/number - title */
			file = g_strdup_printf ("%s - %s" G_DIR_SEPARATOR_S "%s - %s%s",
						artist, album, number, title, ext);
			break;

		default: /* use this for players that don't care */
		case 2:
			/* artist/album/number - title */
			file = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "%s" G_DIR_SEPARATOR_S "%s - %s%s",
						artist, album, number, title, ext);
			break;
		}
		g_free (number);
	}

	g_free (artist);
	g_free (album);
	g_free (title);
	g_free (ext);

	if (file == NULL)
		return NULL;

	g_object_get (priv->device_info, "audio-folders", &audio_folders, NULL);
	if (audio_folders != NULL && g_strv_length (audio_folders) > 0) {
		folders = g_strdup (audio_folders[0]);
	} else {
		folders = "";
	}
	g_strfreev (audio_folders);

	mount_path = rb_generic_player_source_get_mount_path (RB_GENERIC_PLAYER_SOURCE (source));
	path = g_build_filename (mount_path, folders, file, NULL);
	g_free (file);
	g_free (mount_path);

	/* TODO: check for duplicates, or just overwrite by default? */
	rb_debug ("dest file is %s", path);
	return path;
}
static int lookup_one(struct autofs_point *ap,
		char *qKey, int qKey_len, struct lookup_context *ctxt)
{
	struct map_source *source;
	struct mapent_cache *mc;
	struct mapent *we;
	void *sss_ctxt = NULL;
	time_t age = time(NULL);
	char buf[MAX_ERR_BUF];
	char *value = NULL;
	char *s_key;
	int ret;

	source = ap->entry->current;
	ap->entry->current = NULL;
	master_source_current_signal(ap->entry);

	mc = source->mc;

	if (!setautomntent(ap->logopt, ctxt, ctxt->mapname, &sss_ctxt))
		return NSS_STATUS_UNAVAIL;

	ret = ctxt->getautomntbyname_r(qKey, &value, sss_ctxt);
	if (ret && ret != ENOENT) {
		char *estr = strerror_r(ret, buf, MAX_ERR_BUF);
		error(ap->logopt,
		      MODPREFIX "getautomntbyname_r: %s", estr);
		endautomntent(ap->logopt, ctxt, &sss_ctxt);
		if (value)
			free(value);
		return NSS_STATUS_UNAVAIL;
	}
	if (ret != ENOENT) {
		/*
		 * TODO: implement sun % hack for key translation for
		 * mixed case keys in schema that are single case only.
		 */
		s_key = sanitize_path(qKey, qKey_len, ap->type, ap->logopt);
		if (!s_key) {
			free(value);
			value = NULL;
			goto wild;
		}
		cache_writelock(mc);
		ret = cache_update(mc, source, s_key, value, age);
		cache_unlock(mc);
		endautomntent(ap->logopt, ctxt, &sss_ctxt);
		free(s_key);
		free(value);
		return NSS_STATUS_SUCCESS;
	}

wild:
	ret = ctxt->getautomntbyname_r("/", &value, sss_ctxt);
	if (ret && ret != ENOENT) {
		char *estr = strerror_r(ret, buf, MAX_ERR_BUF);
		error(ap->logopt,
		      MODPREFIX "getautomntbyname_r: %s", estr);
		endautomntent(ap->logopt, ctxt, &sss_ctxt);
		if (value)
			free(value);
		return NSS_STATUS_UNAVAIL;
	}
	if (ret == ENOENT) {
		ret = ctxt->getautomntbyname_r("*", &value, sss_ctxt);
		if (ret && ret != ENOENT) {
			char *estr = strerror_r(ret, buf, MAX_ERR_BUF);
			error(ap->logopt,
			      MODPREFIX "getautomntbyname_r: %s", estr);
			endautomntent(ap->logopt, ctxt, &sss_ctxt);
			if (value)
				free(value);
			return NSS_STATUS_UNAVAIL;
		}
	}

	if (ret == ENOENT) {
		/* Failed to find wild entry, update cache if needed */
		cache_writelock(mc);
		we = cache_lookup_distinct(mc, "*");
		if (we) {
			/* Wildcard entry existed and is now gone */
			if (we->source == source) {
				cache_delete(mc, "*");
				source->stale = 1;
			}
		}

		/* Not found in the map but found in the cache */
		struct mapent *exists = cache_lookup_distinct(mc, qKey);
		if (exists && exists->source == source) {
			if (exists->mapent) {
				free(exists->mapent);
				exists->mapent = NULL;
				source->stale = 1;
				exists->status = 0;
			}
		}
		cache_unlock(mc);
		endautomntent(ap->logopt, ctxt, &sss_ctxt);
		return NSS_STATUS_NOTFOUND;
	}

	cache_writelock(mc);
	/* Wildcard not in map but now is */
	we = cache_lookup_distinct(mc, "*");
	if (!we)
		source->stale = 1;
	ret = cache_update(mc, source, "*", value, age);
	cache_unlock(mc);

	endautomntent(ap->logopt, ctxt, &sss_ctxt);
        free(value);

	return NSS_STATUS_SUCCESS;
}
Exemple #20
0
int main(int argc, char **argv) {

  regex_count_t k;
  FILE *input;
  signed char op;


  void (*preprocess_fun)(void) = NULL;
  void (*postprocess_fun)(void) = NULL;


  progname = "mailinspect";
  inputfile = "stdin";
  inputline = 0;

  /* set up internationalization */
  if( !setlocale(LC_ALL, "") ) {
    errormsg(E_WARNING,
	    "could not set locale, internationalization disabled\n");
  } else {
    if( u_options & (1<<U_OPTION_VERBOSE) ) {
      errormsg(E_WARNING,
	      "international locales not supported\n");
    }
  }

#if defined(HAVE_GETPAGESIZE)
  system_pagesize = getpagesize();
#endif

  if( system_pagesize == -1 ) { system_pagesize = BUFSIZ; }

  /* parse the options */
  while( (op = getopt(argc, argv, "c:g:G:iIjo:p:s:VzZ")) > -1 ) {

    switch(op) {
    case 'j':
      m_options |= (1<<M_OPTION_CASEN);
      break;
    case 'I':
      u_options |= (1<<U_OPTION_INTERACTIVE);
      break;

    case 'V':
      fprintf(stdout, "mailinspect version %s\n", VERSION);
      fprintf(stdout, COPYBLURB, "mailinspect");
      exit(1);
      break;

    case 'z':
      u_options |= (1<<U_OPTION_REVSORT);
      break;

    case 'o':
      if( !*optarg ) {
	errormsg(E_ERROR, "you need a number with the -o switch\n");
	usage(argv);
	exit(0);
      }
      u_options |= (1<<U_OPTION_SCORES);
      if( (emails.score_type = atoi(optarg)) >= MAX_SCORES ) {
	emails.score_type = 0;
      }
      break;

    case 'p':
      if( !*optarg ) {
	errormsg(E_ERROR, "you need a number with the -p switch\n");
	usage(argv);
	exit(0);
      }
      u_options |= (1<<U_OPTION_FORMAT);
      if( (emails.index_format = atoi(optarg)) >= MAX_FORMATS ) {
	emails.index_format = 0;
      }
      break;

    case 'c':
      if( cat_count >= 1 ) {
	errormsg(E_WARNING,
		"maximum reached, category ignored\n");
      } else {
	u_options |= (1<<U_OPTION_CLASSIFY);

	cat[cat_count].fullfilename = sanitize_path(optarg, "");

	if( !*optarg ) {
	  errormsg(E_ERROR, "category needs a name\n");
	  usage(argv);
	  exit(0);
	}
	if( !load_category(&cat[cat_count]) ) {
	  errormsg(E_FATAL,
		  "could not load category %s\n", 
		  cat[cat_count].fullfilename);
	}
	sanitize_model_options(&m_options, &m_cp, &cat[cat_count]);
	cat_count++;
      }
      break;

    case 'G':
    case 'g':
      tagre_inclex[tagre_count] = (op == 'g') ? TAGRE_INCLUDE : TAGRE_EXCLUDE;
      if( regcomp(&tagre[tagre_count].regex, optarg, regcomp_flags) != 0 ) {
	errormsg(E_WARNING,
		 "could not compile regular expression '%s', ignored\n", 
		 optarg);
      } else {
	tagre[tagre_count].string = optarg;
	tagre_count++;
      }
      break;

    case 'i':
      m_options |= (1<<M_OPTION_I18N);
#if defined HAVE_LANGINFO_H
      if( !strcmp(nl_langinfo(CODESET), "UTF-8") ) {
	errormsg(E_WARNING, "you have UTF-8, so -i is not needed.\n");
      }
#endif
      break;


    case 's':
      execute_command = optarg;
      break;

    default:
      break;
    }
  }
  
  /* end option processing */
    
  /* consistency checks */
  if( !(u_options & (1<<U_OPTION_CLASSIFY)) ) {
    errormsg(E_ERROR,
	    "please use -c option\n");
    usage(argv);
    exit(0);
  }

  if( !(u_options & (1<<U_OPTION_FORMAT)) ) {
    if( u_options & (1<<U_OPTION_INTERACTIVE) ) {
      emails.index_format = 1;
    } else {
      emails.index_format = 0;
    }
  }
  if( !(u_options & (1<<U_OPTION_SCORES)) ) {
    emails.score_type = 0;
  }
  if( m_options & (1<<M_OPTION_CASEN) ) {
    regcomp_flags = REG_EXTENDED|REG_NOSUB;
  } else {
    regcomp_flags = REG_EXTENDED|REG_NOSUB|REG_ICASE;
  }

  /* setup */

  if( m_options & (1<<M_OPTION_CALCENTROPY) ) {
    init_empirical(&empirical, 
		   default_max_tokens, 
		   default_max_hash_bits); /* sets cached to zero */
  }

  init_file_handling();
  init_emails();

  /* now do processing */

  if( preprocess_fun ) { (*preprocess_fun)(); }

  /* now process the first file on the command line */
  if( (optind > -1) && *(argv + optind) ) {
    /* if it's a filename, process it */
    if( (input = fopen(argv[optind], "rb")) ) {


      if( cat[0].model_num_docs == 0 ) {
	errormsg(E_WARNING,
		"category %s was not created for emails."
		" Messages may not be sorted optimally.\n", cat[0].filename);
      }
      
      if( u_options & (1<<U_OPTION_INTERACTIVE) ) {
	fprintf(stderr,
		"Reading %s, please wait...\n", argv[optind]);
      }

      emails.filename = argv[optind];
      read_mbox_and_sort_list(input);

      fclose(input);

      if( u_options & (1<<U_OPTION_REVSORT) ) {
	reverse_sort();
      }

      if( u_options & (1<<U_OPTION_INTERACTIVE) ) {
#if defined COMPILE_INTERACTIVE_MODE	
	display_results_interactively();
#else
	errormsg(E_ERROR,
		 "\n"
		 "       sorry, interactive mode not available.\n"
		 "       Make sure you have libslang and libreadline\n"
		 "       on your system and reconfigure/recompile.\n");
#endif
      } else {
	if( execute_command ) {
	  pipe_all_to_command(execute_command);
	} else {
	  display_results(stdout);
	}
      }


    } else {

      errormsg(E_ERROR, "couldn't open %s\n", argv[optind]);
      usage(argv);
      exit(0);

    }
  } else {
    errormsg(E_ERROR, "no mbox file specified.\n");
    usage(argv);
    exit(0);
  }
  
  if( postprocess_fun ) { (*postprocess_fun)(); }

  cleanup_file_handling();

  for(k = 0; k < regex_count; k++) {
    regfree(&re[k].regex);
  }
  for(k = 0; k < antiregex_count; k++) {
    regfree(&re[k+MAX_RE].regex);
  }

  exit(1);
}
static char *
impl_build_dest_uri (RBTransferTarget *target,
		     RhythmDBEntry *entry,
		     const char *media_type,
		     const char *extension)
{
	RBAndroidSourcePrivate *priv = GET_PRIVATE (target);
	const char *in_artist;
	char *artist, *album, *title;
	gulong track_number, disc_number;
	char *number;
	char *file = NULL;
	char *storage_uri;
	char *uri;
	char *ext;
	GFile *storage = NULL;

	if (extension != NULL) {
		ext = g_strconcat (".", extension, NULL);
	} else {
		ext = g_strdup ("");
	}

	in_artist = rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_ALBUM_ARTIST);
	if (in_artist[0] == '\0') {
		in_artist = rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_ARTIST);
	}
	artist = sanitize_path (in_artist);
	album = sanitize_path (rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_ALBUM));
	title = sanitize_path (rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_TITLE));

	/* we really do need to fix this so untagged entries actually have NULL rather than
	 * a translated string.
	 */
	if (strcmp (artist, _("Unknown")) == 0 && strcmp (album, _("Unknown")) == 0 &&
	    g_str_has_suffix (rhythmdb_entry_get_string (entry, RHYTHMDB_PROP_LOCATION), title)) {
		/* file isn't tagged, so just use the filename as-is, replacing the extension */
		char *p;

		p = g_utf8_strrchr (title, -1, '.');
		if (p != NULL) {
			*p = '\0';
		}
		file = g_strdup_printf ("%s%s", title, ext);
	}

	if (file == NULL) {
		track_number = rhythmdb_entry_get_ulong (entry, RHYTHMDB_PROP_TRACK_NUMBER);
		disc_number = rhythmdb_entry_get_ulong (entry, RHYTHMDB_PROP_DISC_NUMBER);
		if (disc_number > 0)
			number = g_strdup_printf ("%.02u.%.02u", (guint)disc_number, (guint)track_number);
		else
			number = g_strdup_printf ("%.02u", (guint)track_number);

		/* artist/album/number - title */
		file = g_strdup_printf (G_DIR_SEPARATOR_S "%s" G_DIR_SEPARATOR_S "%s" G_DIR_SEPARATOR_S "%s%%20-%%20%s%s",
					artist, album, number, title, ext);
		g_free (number);
	}

	g_free (artist);
	g_free (album);
	g_free (title);
	g_free (ext);

	/* pick storage container to use somehow
	for (l = priv->storage; l != NULL; l = l->next) {
	}
	*/
	if (priv->storage)
		storage = priv->storage->data;

	if (storage == NULL) {
		rb_debug ("couldn't find a container to store anything in");
		g_free (file);
		return NULL;
	}

	storage_uri = g_file_get_uri (storage);
	uri = g_strconcat (storage_uri, file, NULL);
	g_free (file);
	g_free (storage_uri);

	return uri;
}
int lookup_read_map(struct autofs_point *ap, time_t age, void *context)
{
	struct lookup_context *ctxt = (struct lookup_context *) context;
	struct map_source *source;
	struct mapent_cache *mc;
	void *sss_ctxt = NULL;
	char buf[MAX_ERR_BUF];
	char *key;
	char *value = NULL;
	char *s_key;
	int count, ret;

	source = ap->entry->current;
	ap->entry->current = NULL;
	master_source_current_signal(ap->entry);

	mc = source->mc;

	/*
	 * If we don't need to create directories then there's no use
	 * reading the map. We always need to read the whole map for
	 * direct mounts in order to mount the triggers.
	 */
	if (!(ap->flags & MOUNT_FLAG_GHOST) && ap->type != LKP_DIRECT) {
		debug(ap->logopt, "map read not needed, so not done");
		return NSS_STATUS_SUCCESS;
	}

	if (!setautomntent(ap->logopt, ctxt, ctxt->mapname, &sss_ctxt))
		return NSS_STATUS_UNAVAIL;

	count = 0;
	while (1) {
	        key = NULL;
	        value = NULL;
		ret = ctxt->getautomntent_r(&key, &value, sss_ctxt);
		if (ret && ret != ENOENT) {
			char *estr = strerror_r(ret, buf, MAX_ERR_BUF);
			error(ap->logopt,
			      MODPREFIX "getautomntent_r: %s", estr);
			endautomntent(ap->logopt, ctxt, &sss_ctxt);
			if (key)
				free(key);
			if (value)
				free(value);
			return NSS_STATUS_UNAVAIL;
		}
		if (ret == ENOENT) {
			if (!count) {
				char *estr = strerror_r(ret, buf, MAX_ERR_BUF);
				error(ap->logopt,
				      MODPREFIX "getautomntent_r: %s", estr);
				endautomntent(ap->logopt, ctxt, &sss_ctxt);
				if (key)
					free(key);
				if (value)
					free(value);
				return NSS_STATUS_NOTFOUND;
			}
			break;
		}

		/*
		 * Ignore keys beginning with '+' as plus map
		 * inclusion is only valid in file maps.
		 */
		if (*key == '+') {
			warn(ap->logopt,
			     MODPREFIX "ignoring '+' map entry - not in file map");
			free(key);
			free(value);
			continue;
		}

		if (*key == '/' && strlen(key) == 1) {
			if (ap->type == LKP_DIRECT) {
				free(key);
				free(value);
				continue;
			}
			*key = '*';
		}

		/*
		 * TODO: implement sun % hack for key translation for
		 * mixed case keys in schema that are single case only.
		 */

		s_key = sanitize_path(key, strlen(key), ap->type, ap->logopt);
		if (!s_key) {
			error(ap->logopt, MODPREFIX "invalid path %s", key);
			endautomntent(ap->logopt, ctxt, &sss_ctxt);
			free(key);
			free(value);
			return NSS_STATUS_NOTFOUND;
		}

		count++;

		cache_writelock(mc);
		cache_update(mc, source, s_key, value, age);
		cache_unlock(mc);

		free(s_key);
		free(key);
		free(value);
	}

	endautomntent(ap->logopt, ctxt, &sss_ctxt);

	source->age = age;

	return NSS_STATUS_SUCCESS;
}
Exemple #23
0
 void create_dir(std::string filename)
 {
     filename = sanitize_path(filename);
     python_run(elib::fmt("create_dir('%s')", filename));
 }