+/* Computes the depth of the given path, excluding any basename. This
+ * assumes that the path does not walk through any symlinks.
+ *
+ * For use with unsafe_symlink. */
+int path_depth(const char *path)
+{
+ const char *name, *slash;
+ int depth = 0;
+
+ for (name = path; (slash = strchr(name, '/')) != 0; name = slash+1) {
+ /* ".." segment starts the count over. "." segment is ignored. */
+ if (strncmp(name, "./", 2) == 0)
+ ;
+ else if (strncmp(name, "../", 3) == 0)
+ depth = 0;
+ else
+ depth++;
+ while (slash[1] == '/') slash++; /* just in case path isn't clean */
+ }
+ if (strcmp(name, "..") == 0)
+ depth = 0;
+
+ return depth;
+}
+