Ejemplo n.º 1
0
/*
 * Result private functions
 */
static int udb_result_submit (udb_result_t *r, /* {{{ */
    udb_result_preparation_area_t *r_area,
    udb_query_t const *q, udb_query_preparation_area_t *q_area)
{
  value_list_t vl = VALUE_LIST_INIT;
  size_t i;
  int status;

  assert (r != NULL);
  assert (r_area->ds != NULL);
  assert (((size_t) r_area->ds->ds_num) == r->values_num);
  assert (r->values_num > 0);

  vl.values = calloc (r->values_num, sizeof (*vl.values));
  if (vl.values == NULL)
  {
    ERROR ("db query utils: calloc failed.");
    return (-1);
  }
  vl.values_len = r_area->ds->ds_num;

  for (i = 0; i < r->values_num; i++)
  {
    char *value_str = r_area->values_buffer[i];

    if (0 != parse_value (value_str, &vl.values[i], r_area->ds->ds[i].type))
    {
      ERROR ("db query utils: udb_result_submit: Parsing `%s' as %s failed.",
          value_str, DS_TYPE_TO_STRING (r_area->ds->ds[i].type));
      errno = EINVAL;
      free (vl.values);
      return (-1);
    }
  }

  if (q_area->interval > 0)
    vl.interval = q_area->interval;

  sstrncpy (vl.host, q_area->host, sizeof (vl.host));
  sstrncpy (vl.plugin, q_area->plugin, sizeof (vl.plugin));
  sstrncpy (vl.plugin_instance, q_area->db_name, sizeof (vl.plugin_instance));
  sstrncpy (vl.type, r->type, sizeof (vl.type));

  /* Set vl.type_instance {{{ */
  if (r->instances_num == 0)
  {
    if (r->instance_prefix == NULL)
      vl.type_instance[0] = 0;
    else
      sstrncpy (vl.type_instance, r->instance_prefix,
          sizeof (vl.type_instance));
  }
  else /* if ((r->instances_num > 0) */
  {
    if (r->instance_prefix == NULL)
    {
      strjoin (vl.type_instance, sizeof (vl.type_instance),
          r_area->instances_buffer, r->instances_num, "-");
    }
    else
    {
      char tmp[DATA_MAX_NAME_LEN];

      strjoin (tmp, sizeof (tmp), r_area->instances_buffer,
          r->instances_num, "-");
      tmp[sizeof (tmp) - 1] = 0;

      snprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s",
          r->instance_prefix, tmp);
    }
  }
  vl.type_instance[sizeof (vl.type_instance) - 1] = 0;
  /* }}} */

  /* Annotate meta data. {{{ */
  if (r->metadata_num > 0)
  {
    vl.meta = meta_data_create ();
    if (vl.meta == NULL)
    {
      ERROR ("db query utils:: meta_data_create failed.");
      return (-ENOMEM);
    }

    for (i = 0; i < r->metadata_num; i++)
    {
      status = meta_data_add_string (vl.meta, r->metadata[i],
          r_area->metadata_buffer[i]);
      if (status != 0)
      {
        ERROR ("db query utils:: meta_data_add_string failed.");
        meta_data_destroy (vl.meta);
        vl.meta = NULL;
        return (status);
      }
    }
  }
  /* }}} */

  plugin_dispatch_values (&vl);

  if (r->metadata_num > 0)
  {
    meta_data_destroy (vl.meta);
    vl.meta = NULL;
  }
  sfree (vl.values);
  return (0);
} /* }}} void udb_result_submit */
Ejemplo n.º 2
0
int main(int argc, char *argv[]) {
        int r, output_flags;

        log_parse_environment();
        log_open();

        r = parse_argv(argc, argv);
        if (r <= 0)
                goto finish;

        if (!arg_no_pager) {
                r = pager_open(false);
                if (r > 0 && arg_full < 0)
                        arg_full = true;
        }

        output_flags =
                arg_all * OUTPUT_SHOW_ALL |
                (arg_full > 0) * OUTPUT_FULL_WIDTH;

        if (optind < argc) {
                _cleanup_free_ char *root = NULL;
                int i;

                r = get_cgroup_root(&root);
                if (r < 0)
                        goto finish;

                for (i = optind; i < argc; i++) {
                        int q;

                        if (path_startswith(argv[i], "/sys/fs/cgroup")) {

                                printf("Directory %s:\n", argv[i]);
                                fflush(stdout);

                                q = show_cgroup_by_path(argv[i], NULL, 0, arg_kernel_threads, output_flags);
                        } else {
                                _cleanup_free_ char *c = NULL, *p = NULL, *j = NULL;
                                const char *controller, *path;

                                r = cg_split_spec(argv[i], &c, &p);
                                if (r < 0) {
                                        log_error_errno(r, "Failed to split argument %s: %m", argv[i]);
                                        goto finish;
                                }

                                controller = c ?: SYSTEMD_CGROUP_CONTROLLER;
                                if (p) {
                                        j = strjoin(root, "/", p, NULL);
                                        if (!j) {
                                                r = log_oom();
                                                goto finish;
                                        }

                                        path_kill_slashes(j);
                                        path = j;
                                } else
                                        path = root;

                                show_cg_info(controller, path);

                                q = show_cgroup(controller, path, NULL, 0, arg_kernel_threads, output_flags);
                        }

                        if (q < 0)
                                r = q;
                }

        } else {
Ejemplo n.º 3
0
int playback(FILE * streamfd, int pipefd) {
	killed = 0;
	signal(SIGUSR1, sighand);

#ifndef EXTERN_ONLY
	if(!haskey(& rc, "extern")) {
		const char * freetrack = NULL;

		struct stream data;
		struct mad_decoder dec;

#ifdef LIBAO
		static int ao_initialized = 0;

		if(!ao_initialized) {
			ao_initialize();
			ao_initialized = !0;
		}
#else
		unsigned arg;
		int fd;
#endif

		memset(& data, 0, sizeof(struct stream));

		/*
			Check if there's a stream timeout configured and set it up for timed
			reads later.
		*/
		data.timeout = -1;
		if(haskey(& rc, "stream-timeout")) {
			const char * timeout = value(& rc, "stream-timeout");
			data.timeout = atoi(timeout);

			if(data.timeout <= 0) {
				if(data.timeout < 0) 
					fputs("Invalid stream-timeout.\n", stderr);

				data.timeout = -1;
			}
		}


		data.streamfd = streamfd;
		data.parent = getppid();
		data.pipefd = pipefd;
		fcntl(pipefd, F_SETFL, O_NONBLOCK);

#ifdef LIBAO
		data.driver_id = ao_default_driver_id();

		if(-1 == data.driver_id) {
			fputs("Unable to find any usable output device!\n", stderr);
			return 0;
		}

		data.fmt.bits = 16;
		data.fmt.rate = 44100;
		data.fmt.channels = 2;
		data.fmt.byte_format = AO_FMT_NATIVE;
		data.device = ao_open_live(data.driver_id,&data.fmt,NULL);

		if(NULL == data.device) {
			fprintf(stderr, "Unable to open device. %s.\n", strerror(errno));
			return 0;
		}
#else
		data.audiofd = fd = open(value(& rc, "device"), O_WRONLY);

		if(-1 == data.audiofd) {
			fprintf(
					stderr, "Couldn't open %s! %s.\n",
					value(& rc, "device"), strerror(errno)
			);
			return 0;
		}

		arg = 16; /* 16 bits */
		ioctl(data.audiofd, SOUND_PCM_WRITE_BITS, & arg);
#endif

		freetrack = value(& track, "freeTrackURL");

		if(freetrack && strlen(freetrack) > 0 && haskey(& rc, "download")) {
			char * dnam;
			int rv;

			data.finpath = strdup(meta(value(& rc, "download"), M_RELAXPATH, & track));
			assert(data.finpath != NULL);

			data.tmppath = strjoin("", data.finpath, ".streaming", NULL);
			assert(data.tmppath != NULL);

			dnam = strdup(data.tmppath);
			rv = dnam ? mkpath(dirname(dnam)) : -1;
			free(dnam);

			if(access(data.tmppath, R_OK) == -1) {
				data.dump = (rv == 0) ? fopen(data.tmppath, "w") : NULL;

				if(!data.dump)
					fprintf(stderr, "Can't write download to %s.\n", data.tmppath);
			}
			else {
				data.dump = NULL;
			}
		}

		mad_decoder_init(& dec, & data, input, NULL, NULL, output, NULL, NULL);
		mad_decoder_run(& dec, MAD_DECODER_MODE_SYNC);
#ifndef LIBAO
		close(fd);
#endif
		mad_decoder_finish(& dec);

		if(data.dump) {
			fclose(data.dump);

			if(killed) {
				unlink(data.tmppath);
			} else {
				int rv;
#ifdef TAGLIB
				TagLib_File *tagme = taglib_file_new_type(data.tmppath, TagLib_File_MPEG);
				if(tagme != NULL) {
					TagLib_Tag *tag = taglib_file_tag(tagme);
					taglib_tag_set_title(tag, value(&track, "title"));
					taglib_tag_set_artist(tag, value(&track, "creator"));
					taglib_tag_set_album(tag, value(&track, "album"));
					taglib_file_save(tagme);
					taglib_file_free(tagme);
				}
#endif
				if(haskey(& rc, "pp-cmd")) {
					const char *ppcmd = value(& rc, "pp-cmd");
					size_t ppcmdlen = strlen(ppcmd);
					char *path = shellescape(data.tmppath);
					assert(path != NULL);
					size_t pathlen = strlen(path);
					char *command = malloc(ppcmdlen + pathlen + 2);
					assert(command != NULL);
					memcpy(command, ppcmd, ppcmdlen);
					command[ppcmdlen] = ' ';
					memcpy(command + ppcmdlen + 1, path, pathlen);
					command[ppcmdlen + 1 + pathlen] = 0;
					run(command);
					free(path);
					free(command);
				}

				rv = rename(data.tmppath, data.finpath);
				if (rv == -1)
					fprintf(stderr, "Can't rename %s to %s\n",
							data.tmppath, data.finpath);
			}

			free(data.tmppath);
			free(data.finpath);
		}
	}
	else
#endif
	{
		pid_t ppid = getppid(), cpid = 0;
		const char * cmd = meta(value(& rc, "extern"), M_SHELLESC, & track);
		FILE * ext = openpipe(cmd, & cpid);
		unsigned char * buf;

		if(!ext) {
			fprintf(stderr, "Failed to execute external player (%s). %s.\n",
					cmd, strerror(errno));
			return 0;
		}

		if(!(buf = calloc(BUFSIZE + 1, sizeof(unsigned char)))) {
			fputs("Couldn't allocate enough memory for input buffer.\n", stderr);
			fclose(ext);
			return 0;
		}

		while(!feof(streamfd)) {
			signed nbyte = fread(buf, sizeof(unsigned char), BUFSIZE, streamfd);

			if(nbyte > 0) {
				fwrite(buf, sizeof(unsigned char), nbyte, ext);
				fflush(ext);
			}

			if(kill(ppid, 0) == -1 && errno == ESRCH)
				break;

			if(killed)
				break;
		}

		free(buf);
		fclose(ext);

		waitpid(cpid, NULL, 0);
	}

	return !0;
}
Ejemplo n.º 4
0
int main(int argc, char* argv[]) {

        _cleanup_free_ char *core_pid = NULL, *core_uid = NULL, *core_gid = NULL, *core_signal = NULL,
                *core_timestamp = NULL, *core_comm = NULL, *core_exe = NULL, *core_unit = NULL,
                *core_session = NULL, *core_message = NULL, *core_cmdline = NULL, *coredump_data = NULL,
                *core_slice = NULL, *core_cgroup = NULL, *core_owner_uid = NULL,
                *exe = NULL, *comm = NULL, *filename = NULL;
        const char *info[_INFO_LEN];

        _cleanup_close_ int coredump_fd = -1;

        struct iovec iovec[18];
        off_t coredump_size;
        int r, j = 0;
        uid_t uid, owner_uid;
        gid_t gid;
        pid_t pid;
        char *t;

        /* Make sure we never enter a loop */
        prctl(PR_SET_DUMPABLE, 0);

        /* First, log to a safe place, since we don't know what
         * crashed and it might be journald which we'd rather not log
         * to then. */
        log_set_target(LOG_TARGET_KMSG);
        log_open();

        if (argc < INFO_COMM + 1) {
                log_error("Not enough arguments passed from kernel (%d, expected %d).",
                          argc - 1, INFO_COMM + 1 - 1);
                r = -EINVAL;
                goto finish;
        }

        /* Ignore all parse errors */
        parse_config();

        log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage));
        log_debug("Selected compression %s.", yes_no(arg_compress));

        r = parse_uid(argv[INFO_UID + 1], &uid);
        if (r < 0) {
                log_error("Failed to parse UID.");
                goto finish;
        }

        r = parse_pid(argv[INFO_PID + 1], &pid);
        if (r < 0) {
                log_error("Failed to parse PID.");
                goto finish;
        }

        r = parse_gid(argv[INFO_GID + 1], &gid);
        if (r < 0) {
                log_error("Failed to parse GID.");
                goto finish;
        }

        if (get_process_comm(pid, &comm) < 0) {
                log_warning("Failed to get COMM, falling back to the commandline.");
                comm = strv_join(argv + INFO_COMM + 1, " ");
        }

        if (get_process_exe(pid, &exe) < 0)
                log_warning("Failed to get EXE.");

        info[INFO_PID] = argv[INFO_PID + 1];
        info[INFO_UID] = argv[INFO_UID + 1];
        info[INFO_GID] = argv[INFO_GID + 1];
        info[INFO_SIGNAL] = argv[INFO_SIGNAL + 1];
        info[INFO_TIMESTAMP] = argv[INFO_TIMESTAMP + 1];
        info[INFO_COMM] = comm;
        info[INFO_EXE] = exe;

        if (cg_pid_get_unit(pid, &t) >= 0) {

                if (streq(t, SPECIAL_JOURNALD_SERVICE)) {

                        /* If we are journald, we cut things short,
                         * don't write to the journal, but still
                         * create a coredump. */

                        if (arg_storage != COREDUMP_STORAGE_NONE)
                                arg_storage = COREDUMP_STORAGE_EXTERNAL;

                        r = save_external_coredump(info, uid, &filename, &coredump_fd, &coredump_size);
                        if (r < 0)
                                goto finish;

                        r = maybe_remove_external_coredump(filename, coredump_size);
                        if (r < 0)
                                goto finish;

                        log_info("Detected coredump of the journal daemon itself, diverted to %s.", filename);
                        goto finish;
                }

                core_unit = strappend("COREDUMP_UNIT=", t);
        } else if (cg_pid_get_user_unit(pid, &t) >= 0)
                core_unit = strappend("COREDUMP_USER_UNIT=", t);

        if (core_unit)
                IOVEC_SET_STRING(iovec[j++], core_unit);

        /* OK, now we know it's not the journal, hence we can make use
         * of it now. */
        log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
        log_open();

        core_pid = strappend("COREDUMP_PID=", info[INFO_PID]);
        if (core_pid)
                IOVEC_SET_STRING(iovec[j++], core_pid);

        core_uid = strappend("COREDUMP_UID=", info[INFO_UID]);
        if (core_uid)
                IOVEC_SET_STRING(iovec[j++], core_uid);

        core_gid = strappend("COREDUMP_GID=", info[INFO_GID]);
        if (core_gid)
                IOVEC_SET_STRING(iovec[j++], core_gid);

        core_signal = strappend("COREDUMP_SIGNAL=", info[INFO_SIGNAL]);
        if (core_signal)
                IOVEC_SET_STRING(iovec[j++], core_signal);

        if (sd_pid_get_session(pid, &t) >= 0) {
                core_session = strappend("COREDUMP_SESSION=", t);
                free(t);

                if (core_session)
                        IOVEC_SET_STRING(iovec[j++], core_session);
        }

        if (sd_pid_get_owner_uid(pid, &owner_uid) >= 0) {
                r = asprintf(&core_owner_uid,
                             "COREDUMP_OWNER_UID=" UID_FMT, owner_uid);
                if (r > 0)
                        IOVEC_SET_STRING(iovec[j++], core_owner_uid);
        }

        if (sd_pid_get_slice(pid, &t) >= 0) {
                core_slice = strappend("COREDUMP_SLICE=", t);
                free(t);

                if (core_slice)
                        IOVEC_SET_STRING(iovec[j++], core_slice);
        }

        if (comm) {
                core_comm = strappend("COREDUMP_COMM=", comm);
                if (core_comm)
                        IOVEC_SET_STRING(iovec[j++], core_comm);
        }

        if (exe) {
                core_exe = strappend("COREDUMP_EXE=", exe);
                if (core_exe)
                        IOVEC_SET_STRING(iovec[j++], core_exe);
        }

        if (get_process_cmdline(pid, 0, false, &t) >= 0) {
                core_cmdline = strappend("COREDUMP_CMDLINE=", t);
                free(t);

                if (core_cmdline)
                        IOVEC_SET_STRING(iovec[j++], core_cmdline);
        }

        if (cg_pid_get_path_shifted(pid, NULL, &t) >= 0) {
                core_cgroup = strappend("COREDUMP_CGROUP=", t);
                free(t);

                if (core_cgroup)
                        IOVEC_SET_STRING(iovec[j++], core_cgroup);
        }

        core_timestamp = strjoin("COREDUMP_TIMESTAMP=", info[INFO_TIMESTAMP], "000000", NULL);
        if (core_timestamp)
                IOVEC_SET_STRING(iovec[j++], core_timestamp);

        IOVEC_SET_STRING(iovec[j++], "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1");
        IOVEC_SET_STRING(iovec[j++], "PRIORITY=2");

        /* Vacuum before we write anything again */
        coredump_vacuum(-1, arg_keep_free, arg_max_use);

        /* Always stream the coredump to disk, if that's possible */
        r = save_external_coredump(info, uid, &filename, &coredump_fd, &coredump_size);
        if (r < 0)
                /* skip whole core dumping part */
                goto log;

        /* If we don't want to keep the coredump on disk, remove it
         * now, as later on we will lack the privileges for
         * it. However, we keep the fd to it, so that we can still
         * process it and log it. */
        r = maybe_remove_external_coredump(filename, coredump_size);
        if (r < 0)
                goto finish;
        if (r == 0) {
                const char *coredump_filename;

                coredump_filename = strappenda("COREDUMP_FILENAME=", filename);
                IOVEC_SET_STRING(iovec[j++], coredump_filename);
        }

        /* Vacuum again, but exclude the coredump we just created */
        coredump_vacuum(coredump_fd, arg_keep_free, arg_max_use);

        /* Now, let's drop privileges to become the user who owns the
         * segfaulted process and allocate the coredump memory under
         * his uid. This also ensures that the credentials journald
         * will see are the ones of the coredumping user, thus making
         * sure the user himself gets access to the core dump. */
        if (setresgid(gid, gid, gid) < 0 ||
            setresuid(uid, uid, uid) < 0) {
                log_error("Failed to drop privileges: %m");
                r = -errno;
                goto finish;
        }

#ifdef HAVE_ELFUTILS
        /* Try to get a strack trace if we can */
        if (coredump_size <= arg_process_size_max) {
                _cleanup_free_ char *stacktrace = NULL;

                r = coredump_make_stack_trace(coredump_fd, exe, &stacktrace);
                if (r >= 0)
                        core_message = strjoin("MESSAGE=Process ", info[INFO_PID], " (", comm, ") of user ", info[INFO_UID], " dumped core.\n\n", stacktrace, NULL);
                else if (r == -EINVAL)
                        log_warning("Failed to generate stack trace: %s", dwfl_errmsg(dwfl_errno()));
                else
                        log_warning("Failed to generate stack trace: %s", strerror(-r));
        }

        if (!core_message)
#endif
log:
        core_message = strjoin("MESSAGE=Process ", info[INFO_PID], " (", comm, ") of user ", info[INFO_UID], " dumped core.", NULL);
        if (core_message)
                IOVEC_SET_STRING(iovec[j++], core_message);

        /* Optionally store the entire coredump in the journal */
        if (IN_SET(arg_storage, COREDUMP_STORAGE_JOURNAL, COREDUMP_STORAGE_BOTH) &&
            coredump_size <= (off_t) arg_journal_size_max) {
                size_t sz;

                /* Store the coredump itself in the journal */

                r = allocate_journal_field(coredump_fd, (size_t) coredump_size, &coredump_data, &sz);
                if (r >= 0) {
                        iovec[j].iov_base = coredump_data;
                        iovec[j].iov_len = sz;
                        j++;
                }
        }

        r = sd_journal_sendv(iovec, j);
        if (r < 0)
                log_error("Failed to log coredump: %s", strerror(-r));

finish:
        return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
Ejemplo n.º 5
0
static int create_dbus_files(
                const char *path,
                const char *name,
                const char *service,
                const char *exec,
                const char *user,
                const char *type) {

        _cleanup_free_ char *b = NULL, *s = NULL, *lnk = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        int r;

        assert(path);
        assert(name);
        assert(service || exec);

        if (!service) {
                _cleanup_free_ char *a = NULL;

                s = strjoin("dbus-", name, ".service", NULL);
                if (!s)
                        return log_oom();

                a = strjoin(arg_dest_late, "/", s, NULL);
                if (!a)
                        return log_oom();

                f = fopen(a, "wxe");
                if (!f)
                        return log_error_errno(errno, "Failed to create %s: %m", a);

                fprintf(f,
                        "# Automatically generated by systemd-dbus1-generator\n\n"
                        "[Unit]\n"
                        "SourcePath=%s\n"
                        "Description=DBUS1: %s\n"
                        "Documentation=man:systemd-dbus1-generator(8)\n\n"
                        "[Service]\n"
                        "ExecStart=%s\n"
                        "Type=dbus\n"
                        "BusName=%s\n",
                        path,
                        name,
                        exec,
                        name);

                if (user)
                        fprintf(f, "User=%s\n", user);


                if (type) {
                        fprintf(f, "Environment=DBUS_STARTER_BUS_TYPE=%s\n", type);

                        if (streq(type, "system"))
                                fprintf(f, "Environment=DBUS_STARTER_ADDRESS=" DEFAULT_SYSTEM_BUS_ADDRESS "\n");
                        else if (streq(type, "session")) {
                                char *run;

                                run = getenv("XDG_RUNTIME_DIR");
                                if (!run) {
                                        log_error("XDG_RUNTIME_DIR not set.");
                                        return -EINVAL;
                                }

                                fprintf(f, "Environment=DBUS_STARTER_ADDRESS="KERNEL_USER_BUS_ADDRESS_FMT ";" UNIX_USER_BUS_ADDRESS_FMT "\n",
                                        getuid(), run);
                        }
                }

                r = fflush_and_check(f);
                if (r < 0)
                        return log_error_errno(r, "Failed to write %s: %m", a);

                f = safe_fclose(f);

                service = s;
        }

        b = strjoin(arg_dest_late, "/", name, ".busname", NULL);
        if (!b)
                return log_oom();

        f = fopen(b, "wxe");
        if (!f)
                return log_error_errno(errno, "Failed to create %s: %m", b);

        fprintf(f,
                "# Automatically generated by systemd-dbus1-generator\n\n"
                "[Unit]\n"
                "SourcePath=%s\n"
                "Description=DBUS1: %s\n"
                "Documentation=man:systemd-dbus1-generator(8)\n\n"
                "[BusName]\n"
                "Name=%s\n"
                "Service=%s\n"
                "AllowWorld=talk\n",
                path,
                name,
                name,
                service);

        r = fflush_and_check(f);
        if (r < 0)
                return log_error_errno(r, "Failed to write %s: %m", b);

        lnk = strjoin(arg_dest_late, "/" SPECIAL_BUSNAMES_TARGET ".wants/", name, ".busname", NULL);
        if (!lnk)
                return log_oom();

        mkdir_parents_label(lnk, 0755);
        if (symlink(b, lnk))
                return log_error_errno(errno, "Failed to create symlink %s: %m", lnk);

        return 0;
}
Ejemplo n.º 6
0
static int add_swap(
                const char *what,
                struct mntent *me,
                bool noauto,
                bool nofail) {

        _cleanup_free_ char *name = NULL, *unit = NULL, *lnk = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        int r;

        assert(what);
        assert(me);

        if (access("/proc/swaps", F_OK) < 0) {
                log_info("Swap not supported, ignoring fstab swap entry for %s.", what);
                return 0;
        }

        if (detect_container() > 0) {
                log_info("Running in a container, ignoring fstab swap entry for %s.", what);
                return 0;
        }

        r = unit_name_from_path(what, ".swap", &name);
        if (r < 0)
                return log_error_errno(r, "Failed to generate unit name: %m");

        unit = strjoin(arg_dest, "/", name, NULL);
        if (!unit)
                return log_oom();

        f = fopen(unit, "wxe");
        if (!f) {
                if (errno == EEXIST)
                        log_error("Failed to create swap unit file %s, as it already exists. Duplicate entry in /etc/fstab?", unit);
                else
                        log_error_errno(errno, "Failed to create unit file %s: %m", unit);
                return -errno;
        }

        fprintf(f,
                "# Automatically generated by systemd-fstab-generator\n\n"
                "[Unit]\n"
                "SourcePath=/etc/fstab\n"
                "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n\n"
                "[Swap]\n"
                "What=%s\n",
                what);

        if (!isempty(me->mnt_opts) && !streq(me->mnt_opts, "defaults"))
                fprintf(f, "Options=%s\n", me->mnt_opts);

        r = fflush_and_check(f);
        if (r < 0)
                return log_error_errno(r, "Failed to write unit file %s: %m", unit);

        /* use what as where, to have a nicer error message */
        r = generator_write_timeouts(arg_dest, what, what, me->mnt_opts, NULL);
        if (r < 0)
                return r;

        if (!noauto) {
                lnk = strjoin(arg_dest, "/" SPECIAL_SWAP_TARGET,
                              nofail ? ".wants/" : ".requires/", name, NULL);
                if (!lnk)
                        return log_oom();

                mkdir_parents_label(lnk, 0755);
                if (symlink(unit, lnk) < 0)
                        return log_error_errno(errno, "Failed to create symlink %s: %m", lnk);
        }

        return 0;
}
Ejemplo n.º 7
0
static int refresh_one(
    const char *controller,
    const char *path,
    Hashmap *a,
    Hashmap *b,
    unsigned iteration,
    unsigned depth,
    Group **ret) {

    _cleanup_closedir_ DIR *d = NULL;
    Group *ours;
    int r;

    assert(controller);
    assert(path);
    assert(a);

    if (depth > arg_depth)
        return 0;

    r = process(controller, path, a, b, iteration, &ours);
    if (r < 0)
        return r;

    r = cg_enumerate_subgroups(controller, path, &d);
    if (r == -ENOENT)
        return 0;
    if (r < 0)
        return r;

    for (;;) {
        _cleanup_free_ char *fn = NULL, *p = NULL;
        Group *child = NULL;

        r = cg_read_subgroup(d, &fn);
        if (r < 0)
            return r;
        if (r == 0)
            break;

        p = strjoin(path, "/", fn, NULL);
        if (!p)
            return -ENOMEM;

        path_kill_slashes(p);

        r = refresh_one(controller, p, a, b, iteration, depth + 1, &child);
        if (r < 0)
            return r;

        if (arg_recursive &&
                IN_SET(arg_count, COUNT_ALL_PROCESSES, COUNT_USERSPACE_PROCESSES) &&
                child &&
                child->n_tasks_valid &&
                streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {

            /* Recursively sum up processes */

            if (ours->n_tasks_valid)
                ours->n_tasks += child->n_tasks;
            else {
                ours->n_tasks = child->n_tasks;
                ours->n_tasks_valid = true;
            }
        }
    }

    if (ret)
        *ret = ours;

    return 1;
}
Ejemplo n.º 8
0
static int add_swap(
                const char *what,
                struct mntent *me,
                bool noauto,
                bool nofail) {

        _cleanup_free_ char *name = NULL, *unit = NULL, *lnk = NULL, *filtered = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        int r, pri = -1;
        const char *opts;

        assert(what);
        assert(me);

        if (access("/proc/swaps", F_OK) < 0) {
                log_info("Swap not supported, ignoring fstab swap entry for %s.", what);
                return 0;
        }

        if (detect_container(NULL) > 0) {
                log_info("Running in a container, ignoring fstab swap entry for %s.", what);
                return 0;
        }

        opts = me->mnt_opts;
        r = fstab_find_pri(opts, &pri);
        if (r < 0) {
                log_error_errno(r, "Failed to parse priority, ignoring: %m");

                /* Remove invalid pri field */
                r = fstab_filter_options(opts, "pri\0", NULL, NULL, &filtered);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse options: %m");
                opts = filtered;
        }

        name = unit_name_from_path(what, ".swap");
        if (!name)
                return log_oom();

        unit = strjoin(arg_dest, "/", name, NULL);
        if (!unit)
                return log_oom();

        f = fopen(unit, "wxe");
        if (!f) {
                if (errno == EEXIST)
                        log_error("Failed to create swap unit file %s, as it already exists. Duplicate entry in /etc/fstab?", unit);
                else
                        log_error_errno(errno, "Failed to create unit file %s: %m", unit);
                return -errno;
        }

        fprintf(f,
                "# Automatically generated by systemd-fstab-generator\n\n"
                "[Unit]\n"
                "SourcePath=/etc/fstab\n"
                "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n\n"
                "[Swap]\n"
                "What=%s\n",
                what);

        /* Note that we currently pass the priority field twice, once
         * in Priority=, and once in Options= */
        if (pri >= 0)
                fprintf(f, "Priority=%i\n", pri);

        if (!isempty(opts) && !streq(opts, "defaults"))
                fprintf(f, "Options=%s\n", opts);

        r = fflush_and_check(f);
        if (r < 0)
                return log_error_errno(r, "Failed to write unit file %s: %m", unit);

        /* use what as where, to have a nicer error message */
        r = generator_write_timeouts(arg_dest, what, what, opts, NULL);
        if (r < 0)
                return r;

        if (!noauto) {
                lnk = strjoin(arg_dest, "/" SPECIAL_SWAP_TARGET,
                              nofail ? ".wants/" : ".requires/", name, NULL);
                if (!lnk)
                        return log_oom();

                mkdir_parents_label(lnk, 0755);
                if (symlink(unit, lnk) < 0)
                        return log_error_errno(errno, "Failed to create symlink %s: %m", lnk);
        }

        return 0;
}
Ejemplo n.º 9
0
static int parse_argv(int argc, char *argv[]) {

        enum {
                ARG_VERSION = 0x100,
                ARG_ADDRESS,
                ARG_MACHINE,
        };

        static const struct option options[] = {
                { "help",            no_argument,       NULL, 'h'                 },
                { "version",         no_argument,       NULL, ARG_VERSION         },
                { "address",         required_argument, NULL, ARG_ADDRESS         },
                { "machine",         required_argument, NULL, ARG_MACHINE         },
                {},
        };

        int c;

        assert(argc >= 0);
        assert(argv);

        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)

                switch (c) {

                case 'h':
                        help();
                        return 0;

                case ARG_VERSION:
                        puts(PACKAGE_STRING);
                        puts(SYSTEMD_FEATURES);
                        return 0;

                case ARG_ADDRESS: {
                        char *a;

                        a = strdup(optarg);
                        if (!a)
                                return log_oom();

                        free(arg_address);
                        arg_address = a;
                        break;
                }

                case ARG_MACHINE: {
                        _cleanup_free_ char *e = NULL;
                        char *a;

                        e = bus_address_escape(optarg);
                        if (!e)
                                return log_oom();

                        a = strjoin("x-machine-kernel:machine=", e, ";x-machine-unix:machine=", e, NULL);
                        if (!a)
                                return log_oom();

                        free(arg_address);
                        arg_address = a;

                        break;
                }

                case '?':
                        return -EINVAL;

                default:
                        assert_not_reached("Unhandled option");
                }

        /* If the first command line argument is only "x" characters
         * we'll write who we are talking to into it, so that "ps" is
         * explanatory */
        arg_command_line_buffer = argv[optind];
        if (argc > optind + 1 || (arg_command_line_buffer && !in_charset(arg_command_line_buffer, "x"))) {
                log_error("Too many arguments");
                return -EINVAL;
        }

        if (!arg_address) {
                arg_address = strdup(is_kdbus_available() ? KERNEL_SYSTEM_BUS_ADDRESS : UNIX_SYSTEM_BUS_ADDRESS);
                if (!arg_address)
                        return log_oom();
        }

        return 1;
}
Ejemplo n.º 10
0
static int add_mount(
                const char *what,
                const char *where,
                const char *fstype,
                const char *opts,
                int passno,
                bool noauto,
                bool nofail,
                bool automount,
                const char *post,
                const char *source) {

        _cleanup_free_ char
                *name = NULL, *unit = NULL, *lnk = NULL,
                *automount_name = NULL, *automount_unit = NULL,
                *filtered = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        int r;

        assert(what);
        assert(where);
        assert(opts);
        assert(source);

        if (streq_ptr(fstype, "autofs"))
                return 0;

        if (!is_path(where)) {
                log_warning("Mount point %s is not a valid path, ignoring.", where);
                return 0;
        }

        if (mount_point_is_api(where) ||
            mount_point_ignore(where))
                return 0;

        if (path_equal(where, "/")) {
                /* The root disk is not an option */
                automount = false;
                noauto = false;
                nofail = false;
        }

        name = unit_name_from_path(where, ".mount");
        if (!name)
                return log_oom();

        unit = strjoin(arg_dest, "/", name, NULL);
        if (!unit)
                return log_oom();

        f = fopen(unit, "wxe");
        if (!f) {
                if (errno == EEXIST)
                        log_error("Failed to create mount unit file %s, as it already exists. Duplicate entry in /etc/fstab?", unit);
                else
                        log_error_errno(errno, "Failed to create unit file %s: %m", unit);
                return -errno;
        }

        fprintf(f,
                "# Automatically generated by systemd-fstab-generator\n\n"
                "[Unit]\n"
                "SourcePath=%s\n"
                "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n",
                source);

        if (post && !noauto && !nofail && !automount)
                fprintf(f, "Before=%s\n", post);

        if (passno != 0) {
                r = generator_write_fsck_deps(f, arg_dest, what, where, fstype);
                if (r < 0)
                        return r;
        }

        fprintf(f,
                "\n"
                "[Mount]\n"
                "What=%s\n"
                "Where=%s\n",
                what,
                where);

        if (!isempty(fstype) && !streq(fstype, "auto"))
                fprintf(f, "Type=%s\n", fstype);

        r = generator_write_timeouts(arg_dest, what, where, opts, &filtered);
        if (r < 0)
                return r;

        if (!isempty(filtered) && !streq(filtered, "defaults"))
                fprintf(f, "Options=%s\n", filtered);

        fflush(f);
        if (ferror(f))
                return log_error_errno(errno, "Failed to write unit file %s: %m", unit);

        if (!noauto && post) {
                lnk = strjoin(arg_dest, "/", post, nofail || automount ? ".wants/" : ".requires/", name, NULL);
                if (!lnk)
                        return log_oom();

                mkdir_parents_label(lnk, 0755);
                if (symlink(unit, lnk) < 0)
                        return log_error_errno(errno, "Failed to create symlink %s: %m", lnk);
        }

        if (automount) {
                automount_name = unit_name_from_path(where, ".automount");
                if (!automount_name)
                        return log_oom();

                automount_unit = strjoin(arg_dest, "/", automount_name, NULL);
                if (!automount_unit)
                        return log_oom();

                fclose(f);
                f = fopen(automount_unit, "wxe");
                if (!f)
                        return log_error_errno(errno, "Failed to create unit file %s: %m", automount_unit);

                fprintf(f,
                        "# Automatically generated by systemd-fstab-generator\n\n"
                        "[Unit]\n"
                        "SourcePath=%s\n"
                        "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n",
                        source);

                if (post)
                        fprintf(f,
                                "Before=%s\n",
                                post);

                fprintf(f,
                        "[Automount]\n"
                        "Where=%s\n",
                        where);

                fflush(f);
                if (ferror(f))
                        return log_error_errno(errno, "Failed to write unit file %s: %m", automount_unit);

                free(lnk);
                lnk = strjoin(arg_dest, "/", post, nofail ? ".wants/" : ".requires/", automount_name, NULL);
                if (!lnk)
                        return log_oom();

                mkdir_parents_label(lnk, 0755);
                if (symlink(automount_unit, lnk) < 0)
                        return log_error_errno(errno, "Failed to create symlink %s: %m", lnk);
        }

        return 0;
}
Ejemplo n.º 11
0
static int parse_proc_cmdline_item(const char *key, const char *value) {
        int r;

        /* root=, usr=, usrfstype= and roofstype= may occur more than once, the last
         * instance should take precedence.  In the case of multiple rootflags=
         * or usrflags= the arguments should be concatenated */

        if (STR_IN_SET(key, "fstab", "rd.fstab") && value) {

                r = parse_boolean(value);
                if (r < 0)
                        log_warning("Failed to parse fstab switch %s. Ignoring.", value);
                else
                        arg_fstab_enabled = r;

        } else if (streq(key, "root") && value) {

                if (free_and_strdup(&arg_root_what, value) < 0)
                        return log_oom();

        } else if (streq(key, "rootfstype") && value) {

                if (free_and_strdup(&arg_root_fstype, value) < 0)
                        return log_oom();

        } else if (streq(key, "rootflags") && value) {
                char *o;

                o = arg_root_options ?
                        strjoin(arg_root_options, ",", value, NULL) :
                        strdup(value);
                if (!o)
                        return log_oom();

                free(arg_root_options);
                arg_root_options = o;

        } else if (streq(key, "mount.usr") && value) {

                if (free_and_strdup(&arg_usr_what, value) < 0)
                        return log_oom();

        } else if (streq(key, "mount.usrfstype") && value) {

                if (free_and_strdup(&arg_usr_fstype, value) < 0)
                        return log_oom();

        } else if (streq(key, "mount.usrflags") && value) {
                char *o;

                o = arg_usr_options ?
                        strjoin(arg_usr_options, ",", value, NULL) :
                        strdup(value);
                if (!o)
                        return log_oom();

                free(arg_usr_options);
                arg_usr_options = o;

        } else if (streq(key, "rw") && !value)
                arg_root_rw = true;
        else if (streq(key, "ro") && !value)
                arg_root_rw = false;

        return 0;
}
Ejemplo n.º 12
0
void geninter(Tuple to_bind)									/*;geninter*/
{
#ifdef SUPPORT_PRAGMA_INTERFACE
	char *INT_DIR;	/* directory containing partially bound interpreter */
	char *INT_FILE;	/* filename representing partially bound interpreter */
	char *PROC_INTERFACE; /* temporary file containing procedure interface() */
	extern char *LIBRARY_PREFIX; /* user library, defined in misc.c */
	char *argp[80];
#endif
	char *code;
	char dummy_array[80];
	int  i, j, n, m, status;
	FILE *file;
	char *token, *ptr, *s;
	char *exec_name;
#ifdef IBM_PC
	FILE *efopen();
#endif

	/* generation of the procedure interface whith the branches of the case
     * which have been stored in the tuple interfaced_procedures*/
	code = "interface(procedure)\nint procedure;\n{\n";
	code = strjoin(code, "extern float get_float_argument_value();\n");
	code = strjoin(code,
	  "extern int cur_stackptr, *cur_stack;\n switch(procedure){\n");
	n = tup_size(interfaced_procedures);
	m = tup_size(to_bind);
	for (i = 1; i <= n; i+=2) {
		for (j = 1; j <= m; j++) {
			if((int)interfaced_procedures[i] == unit_numbered(to_bind[j])) {
				code = strjoin(code, interfaced_procedures[i+1]);
				break;
			}
		}
	}
	sprintf(dummy_array,
	  "\tdefault: raise(%d, \"Interface\");\n}\n}\n", 6);
	code = strjoin(code, dummy_array);
#ifdef SUPPORT_PRAGMA_INTERFACE
	file = efopenl("interface.c", "", "w", "t");
#endif
#ifdef IBM_PC
	file = efopen("iface.c", "w", "t");
#endif
	fprintf(file, code);
	fclose(file);

#ifdef SUPPORT_PRAGMA_INTERFACE
	PROC_INTERFACE = strjoin(LIBRARY_PREFIX, DIR_DELIMITER);
	PROC_INTERFACE = strjoin(PROC_INTERFACE, "interface.c");

	/* construction of the array argp which is a parameter of execvp */
	argp[0] = "cc";
	argp[1] = PROC_INTERFACE;

	INT_DIR = getenv("INT");
	if (INT_DIR == (char *) 0) {
		user_error("environment variable  INT not set");
		return;
	}
	INT_FILE = strjoin(INT_DIR, "/adaint");
	argp[2] = INT_FILE;

	ptr = interface_files;
	i = 3;
	/* the string interface_files consists of a succession of tokens 
	 * followed by one blank. We break this string into tokens and we check 
	 * whether these tokens contain an 'o' extension or not 
	 */
	while (*ptr != '\0') {
		token = ptr;
		while (*ptr != ' ') ptr++;
		*ptr++ = '\0';
		if (strchr(token, '.') == (char *)0) {
			token = strjoin("-l", token);
			argp[i++] = token;
		}
		else {
			s = strchr(token, '.');
			if ((*(s + 1) == 'o') && (*(s + 2) == '\0')) {
				argp[i++] = token;
			}
			else {
				sprintf(dummy_array, "%s not an object file",token);
				user_error(dummy_array);
				return;
			}
		}
	}

	argp[i++] = "-lm";

	exec_name = strjoin(LIBRARY_PREFIX, DIR_DELIMITER);
	exec_name = strjoin(exec_name, AISFILENAME);
	exec_name = strjoin(exec_name, ".exe");
	argp[i++] = "-o";
	argp[i++] = exec_name;

	argp[i] = (char *) 0;

	if (fork() == 0) {
		exit(execvp("gcc", argp));
	}
	else {
		wait(&status);
		unlink(PROC_INTERFACE);
		unlink("interface.o");
	}
#endif
}
Ejemplo n.º 13
0
Archivo: ss_2.c Proyecto: jddantes/chat
int handle_data(char * data, char * ret){
	/*
		Data structured as: [head] tail
		Returns 1 to self-broadcast
			2 to broadcast to all
			
		
	*/
	char head[200];
	char tail[600];
	int offset = 0;
	offset += getNext(data+offset, head);
	if(!strcmp(head, "LOGIN")){
		char user[200];
		char pass[200];
		offset += getNext(data+offset, user);
		offset += getNext(data+offset, pass);
		int login = verifyLogin(user, pass);
		if(login) {
			strcpy(ret, "[LOGIN_CHK_1] [You have logged in]\n");	
			printf("server: %s logged in\n", user);
		} else {
			strcpy(ret, "[LOGIN_CHK_0] [Incorrect username/password]\n");
		}
		return BROADCAST_SELF;
	} else if(!strcmp(head, "CREATE_ACCT")) {
		char user[200];
		char pass[200];
		offset += getNext(data+offset, user);
		offset += getNext(data+offset, pass);
		createAcct(user, pass);
		strcpy(ret, "[ACCT_CREATED] [Account succesfully created]\n");
		return BROADCAST_SELF;
	} else if(!strcmp(head, "CHK_USR")){
		char user[200];
		offset += getNext(data+offset, user);
		int user_exst = userCheck(user);
		if(user_exst){
			strcpy(ret, "[USR_CHK_1] [User exists]\n");
		} else {
			strcpy(ret, "[USR_CHK_0] [Username is valid]\n");
		}	
		return BROADCAST_SELF;
	} else if(!strcmp(head, "JOIN")){
		char user[200];
		char ts[50];
		offset += getNext(data+offset, user);
		offset += getNext(data+offset, ts);
		strjoin(ret, "[JOINED] [", user, "] [", ts, "]\n", NULL);
		strcpy(user_list[currfd], user);
		ol_list[currfd] = 1;
		//printf("Setting user %d to %s\n", currfd, user);
		return BROADCAST_OTHERS;
	} else if(!strcmp(head, "LEAVE")){
		char user[200];
		char ts[50];
		offset += getNext(data+offset, user);
		offset += getNext(data+offset, ts);
		strjoin(ret, "[LEFT] [", user, "] [", ts, "]\n", NULL);
		user_list[currfd][0] = 0;
		ol_list[currfd] = 0;
		return BROADCAST_OTHERS;
	
	 } else if(!strcmp(head, "MSG")){
		char user[200];
		char ts[50];
		char msg[200];
		offset += getNext(data+offset, user);
		offset += getNext(data+offset, ts);
		offset += getNext(data+offset, msg);
		strjoin(ret, "[MSG] [", user, "] [", ts, "] [", msg, "]\n", NULL);
		return BROADCAST_ALL;
	} else if(!strcmp(head, "OL")){
		strcpy(ret, "[ONLINE]");
		pollOnline(ret);
		return BROADCAST_SELF;
	} else if(!strcmp(head, "PM")){
		//printf("server: Got pm\n");
		char target[200];
		char user[200];
		char ts[50];
		char msg[200];
		offset += getNext(data+offset, target);
		strcpy(pm_global, target);
		offset += getNext(data+offset, user);
		offset += getNext(data+offset, ts);
		offset += getNext(data+offset, msg);
		strjoin(ret, "[PMR] [", user, "] [", ts, "] [", msg, "]\n", NULL);
		return BROADCAST_ONE;
	}
	
}
Ejemplo n.º 14
0
static int files_add(
                Hashmap *h,
                Set *masked,
                const char *suffix,
                const char *root,
                unsigned flags,
                const char *path) {

        _cleanup_closedir_ DIR *dir = NULL;
        const char *dirpath;
        struct dirent *de;
        int r;

        assert(h);
        assert((flags & CONF_FILES_FILTER_MASKED) == 0 || masked);
        assert(path);

        dirpath = prefix_roota(root, path);

        dir = opendir(dirpath);
        if (!dir) {
                if (errno == ENOENT)
                        return 0;

                return log_debug_errno(errno, "Failed to open directory '%s': %m", dirpath);
        }

        FOREACH_DIRENT(de, dir, return -errno) {
                struct stat st;
                char *p, *key;

                /* Does this match the suffix? */
                if (suffix && !endswith(de->d_name, suffix))
                        continue;

                /* Has this file already been found in an earlier directory? */
                if (hashmap_contains(h, de->d_name)) {
                        log_debug("Skipping overridden file '%s/%s'.", dirpath, de->d_name);
                        continue;
                }

                /* Has this been masked in an earlier directory? */
                if ((flags & CONF_FILES_FILTER_MASKED) && set_contains(masked, de->d_name)) {
                        log_debug("File '%s/%s' is masked by previous entry.", dirpath, de->d_name);
                        continue;
                }

                /* Read file metadata if we shall validate the check for file masks, for node types or whether the node is marked executable. */
                if (flags & (CONF_FILES_FILTER_MASKED|CONF_FILES_REGULAR|CONF_FILES_DIRECTORY|CONF_FILES_EXECUTABLE))
                        if (fstatat(dirfd(dir), de->d_name, &st, 0) < 0) {
                                log_debug_errno(errno, "Failed to stat '%s/%s', ignoring: %m", dirpath, de->d_name);
                                continue;
                        }

                /* Is this a masking entry? */
                if ((flags & CONF_FILES_FILTER_MASKED))
                        if (null_or_empty(&st)) {
                                /* Mark this one as masked */
                                r = set_put_strdup(masked, de->d_name);
                                if (r < 0)
                                        return r;

                                log_debug("File '%s/%s' is a mask.", dirpath, de->d_name);
                                continue;
                        }

                /* Does this node have the right type? */
                if (flags & (CONF_FILES_REGULAR|CONF_FILES_DIRECTORY))
                        if (!((flags & CONF_FILES_DIRECTORY) && S_ISDIR(st.st_mode)) &&
                            !((flags & CONF_FILES_REGULAR) && S_ISREG(st.st_mode))) {
                                log_debug("Ignoring '%s/%s', as it is not a of the right type.", dirpath, de->d_name);
                                continue;
                        }

                /* Does this node have the executable bit set? */
                if (flags & CONF_FILES_EXECUTABLE)
                        /* As requested: check if the file is marked exectuable. Note that we don't check access(X_OK)
                         * here, as we care about whether the file is marked executable at all, and not whether it is
                         * executable for us, because if so, such errors are stuff we should log about. */

                        if ((st.st_mode & 0111) == 0) { /* not executable */
                                log_debug("Ignoring '%s/%s', as it is not marked executable.", dirpath, de->d_name);
                                continue;
                        }

                if (flags & CONF_FILES_BASENAME) {
                        p = strdup(de->d_name);
                        if (!p)
                                return -ENOMEM;

                        key = p;
                } else {
                        p = strjoin(dirpath, "/", de->d_name);
                        if (!p)
                                return -ENOMEM;

                        key = basename(p);
                }

                r = hashmap_put(h, key, p);
                if (r < 0) {
                        free(p);
                        return log_debug_errno(r, "Failed to add item to hashmap: %m");
                }

                assert(r > 0);
        }

        return 0;
}
Ejemplo n.º 15
0
static int enumerate_dir_d(Hashmap *top, Hashmap *bottom, Hashmap *drops, const char *toppath, const char *drop) {
        _cleanup_free_ char *unit = NULL;
        _cleanup_free_ char *path = NULL;
        _cleanup_strv_free_ char **list = NULL;
        char **file;
        char *c;
        int r;

        assert(!endswith(drop, "/"));

        path = strjoin(toppath, "/", drop, NULL);
        if (!path)
                return -ENOMEM;

        log_debug("Looking at %s", path);

        unit = strdup(drop);
        if (!unit)
                return -ENOMEM;

        c = strrchr(unit, '.');
        if (!c)
                return -EINVAL;
        *c = 0;

        r = get_files_in_directory(path, &list);
        if (r < 0){
                log_error("Failed to enumerate %s: %s", path, strerror(-r));
                return r;
        }

        STRV_FOREACH(file, list) {
                Hashmap *h;
                int k;
                char *p;
                char *d;

                if (!endswith(*file, ".conf"))
                        continue;

                p = strjoin(path, "/", *file, NULL);
                if (!p)
                        return -ENOMEM;
                d = p + strlen(toppath) + 1;

                log_debug("Adding at top: %s → %s", d, p);
                k = hashmap_put(top, d, p);
                if (k >= 0) {
                        p = strdup(p);
                        if (!p)
                                return -ENOMEM;
                        d = p + strlen(toppath) + 1;
                } else if (k != -EEXIST) {
                        free(p);
                        return k;
                }

                log_debug("Adding at bottom: %s → %s", d, p);
                free(hashmap_remove(bottom, d));
                k = hashmap_put(bottom, d, p);
                if (k < 0) {
                        free(p);
                        return k;
                }

                h = hashmap_get(drops, unit);
                if (!h) {
                        h = hashmap_new(string_hash_func, string_compare_func);
                        if (!h)
                                return -ENOMEM;
                        hashmap_put(drops, unit, h);
                        unit = strdup(unit);
                        if (!unit)
                                return -ENOMEM;
                }

                p = strdup(p);
                if (!p)
                        return -ENOMEM;

                log_debug("Adding to drops: %s → %s → %s", unit, basename(p), p);
                k = hashmap_put(h, basename(p), p);
                if (k < 0) {
                        free(p);
                        if (k != -EEXIST)
                                return k;
                }
        }
Ejemplo n.º 16
0
int main (int argc, char *argv[])
{
    char *s = strjoin(tracks, 5);
    printf("%s\n", s);
    return 0;
}