@@ -495,6 +495,90 @@ count_chars(const char c, const char *str)
495495}
496496
497497
498+ int
499+ validate_path (const char * path )
500+ {
501+ if (!path )
502+ {
503+ fprintf (stderr , "Error: Path is NULL.\n" );
504+ return -1 ; // Invalid input
505+ }
506+
507+ // Query dynamic limits
508+ long path_max = pathconf ("/" , _PC_PATH_MAX );
509+ if (path_max == -1 )
510+ {
511+ if (errno == 0 )
512+ {
513+ path_max = PATH_MAX ; // Use fallback if no limit
514+ }
515+ else
516+ {
517+ perror ("pathconf for PATH_MAX" );
518+ return -1 ;
519+ }
520+ }
521+
522+ long name_max = pathconf ("/" , _PC_NAME_MAX );
523+ if (name_max == -1 )
524+ {
525+ if (errno == 0 )
526+ {
527+ name_max = NAME_MAX ; // Use fallback if no limit
528+ }
529+ else
530+ {
531+ perror ("pathconf for NAME_MAX" );
532+ return -1 ;
533+ }
534+ }
535+
536+ size_t path_len = strlen (path );
537+ if (path_len > (size_t ) path_max )
538+ {
539+ fprintf (stderr , "Error: Path length (%zu) exceeds PATH_MAX (%ld).\n" ,
540+ path_len , path_max );
541+ return -1 ;
542+ }
543+
544+ // Check individual component lengths
545+ const char * start = path ;
546+ while (* start )
547+ {
548+ const char * end = strchr (start , '/' );
549+ size_t component_len = end ? (size_t ) (end - start ) : strlen (start );
550+
551+ if (component_len > (size_t ) name_max )
552+ {
553+ fprintf (stderr ,
554+ "Error: Path component '%.*s' exceeds NAME_MAX (%ld).\n" ,
555+ (int ) component_len , start , name_max );
556+ return -1 ;
557+ }
558+
559+ if (!end )
560+ {
561+ break ;
562+ }
563+ start = end + 1 ;
564+ }
565+
566+ return 0 ;
567+ }
568+
569+ //int main() {
570+ //const char *test_path = "/home/user/documents/very_long_filename.txt";
571+
572+ //if (validate_path(test_path) == 0) {
573+ //printf("The path '%s' is valid.\n", test_path);
574+ //} else {
575+ //printf("The path '%s' is invalid.\n", test_path);
576+ //}
577+
578+ //return 0;
579+ //}
580+
581+
498582///////////////////////////////////////////////////////////////////////
499583#ifdef TEST_LIB
500584
@@ -723,6 +807,15 @@ test_count_chars(void)
723807 return ;
724808}
725809
810+ void
811+ test_validate_path (void )
812+ {
813+ assert (validate_path
814+ ("/dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd/foo" )
815+ != 0 );
816+ return ;
817+ }
818+
726819
727820int
728821main ()
@@ -756,6 +849,8 @@ main()
756849 free (escaped_path );
757850
758851 test_count_chars ();
852+
853+ test_validate_path ();
759854 return 0 ;
760855}
761856#endif
0 commit comments