+static
+enum fs_writer_stream_state *insert_new_stream_state(
+ struct writer_component *writer_component,
+ struct fs_writer *fs_writer, struct bt_ctf_stream *stream)
+{
+ enum fs_writer_stream_state *v = NULL;
+
+ v = g_new0(enum fs_writer_stream_state, 1);
+ if (!v) {
+ fprintf(writer_component->err,
+ "[error] %s in %s:%d\n", __func__,
+ __FILE__, __LINE__);
+ }
+ *v = FS_WRITER_UNKNOWN_STREAM;
+
+ g_hash_table_insert(fs_writer->stream_states, stream, v);
+
+ return v;
+}
+
+/*
+ * Make sure the output path is valid for a single trace: either it does
+ * not exists or it is empty.
+ *
+ * Return 0 if the path is valid, -1 otherwise.
+ */
+static
+bool valid_single_trace_path(const char *path)
+{
+ int n = 0;
+ struct dirent *d;
+ DIR *dir = opendir(path);
+ int ret;
+
+ /* Non-existent directory. */
+ if (!dir) {
+ ret = 0;
+ goto end;
+ }
+
+ while ((d = readdir(dir)) != NULL) {
+ /* Ignore "." and ".." directories. */
+ if (++n > 2) {
+ break;
+ }
+ }
+
+ ret = closedir(dir);
+ if (ret) {
+ perror("closedir");
+ goto end;
+ }
+
+ if (n <= 2) {
+ ret = 0;
+ } else {
+ ret = -1;
+ }
+
+end:
+ return ret;
+}
+
+static
+int make_trace_path(struct writer_component *writer_component,
+ struct bt_ctf_trace *trace, char *trace_path)
+{
+ int ret;
+ const char *trace_name;
+
+ if (writer_component->single_trace) {
+ trace_name = "\0";
+ } else {
+ trace_name = bt_ctf_trace_get_name(trace);
+ if (!trace_name) {
+ trace_name = writer_component->trace_name_base->str;
+ }
+ }
+
+ /* Sanitize the trace name. */
+ if (strlen(trace_name) == 2 && !strcmp(trace_name, "..")) {
+ fprintf(writer_component->err, "[error] Trace name cannot "
+ "be \"..\"\n");
+ goto error;
+ }
+
+ if (strstr(trace_name, "../")) {
+ fprintf(writer_component->err, "[error] Trace name cannot "
+ "contain \"../\", received \"%s\"\n",
+ trace_name);
+ goto error;
+
+ }
+
+ snprintf(trace_path, PATH_MAX, "%s/%s",
+ writer_component->base_path->str,
+ trace_name);
+ /*
+ * Append a suffix if the trace_path exists and we are not in
+ * single-trace mode.
+ */
+ if (writer_component->single_trace) {
+ if (valid_single_trace_path(trace_path) != 0) {
+ fprintf(writer_component->err,
+ "[error] Invalid output directory\n");
+ goto error;
+ }
+ } else {
+ if (g_file_test(trace_path, G_FILE_TEST_EXISTS)) {
+ int i = 0;
+
+ do {
+ snprintf(trace_path, PATH_MAX, "%s/%s-%d",
+ writer_component->base_path->str,
+ trace_name, ++i);
+ } while (g_file_test(trace_path, G_FILE_TEST_EXISTS) && i < INT_MAX);
+ if (i == INT_MAX) {
+ fprintf(writer_component->err, "[error] Unable to find "
+ "a unique trace path\n");
+ goto error;
+ }
+ }
+ }
+
+ ret = 0;
+ goto end;
+
+error:
+ ret = -1;
+end:
+ return ret;
+}
+