@@ -13,7 +13,6 @@ import (
1313)
1414
1515type CreateOptions struct {
16- // Root defaults to "/" if empty.
1716 Root string
1817 // Path is relative to Root.
1918 Path string
@@ -49,10 +48,17 @@ func Create(options *CreateOptions) (*Entry, error) {
4948 optsCopy .Data = rp
5049 o := & optsCopy
5150
52- err := setValidPath (o )
51+ if o .Root == "" {
52+ return nil , fmt .Errorf ("root cannot be empty" )
53+ }
54+ if o .Root != "/" {
55+ o .Root = filepath .Clean (o .Root ) + "/"
56+ }
57+ path , err := absPath (o .Root , o .Path )
5358 if err != nil {
5459 return nil , err
5560 }
61+ o .Path = path
5662
5763 var hash string
5864 if o .MakeParents {
@@ -66,7 +72,7 @@ func Create(options *CreateOptions) (*Entry, error) {
6672 if o .Link != "" {
6773 o .Link = filepath .Clean (o .Link )
6874 if filepath .IsAbs (o .Link ) {
69- if ! strings .HasPrefix (o .Link , o .Root ) {
75+ if ! strings .HasPrefix (filepath . Clean ( o .Link ) , o .Root ) {
7076 return nil , fmt .Errorf ("invalid hardlink %s target: %s is outside of root %s" , o .Path , o .Link , o .Root )
7177 }
7278 }
@@ -125,16 +131,23 @@ func CreateWriter(options *CreateOptions) (io.WriteCloser, *Entry, error) {
125131 optsCopy := * options
126132 o := & optsCopy
127133
128- err := setValidPath (o )
134+ if o .Root == "" {
135+ return nil , nil , fmt .Errorf ("root cannot be empty" )
136+ }
137+ if o .Root != "/" {
138+ o .Root = filepath .Clean (o .Root ) + "/"
139+ }
140+ path , err := absPath (o .Root , o .Path )
129141 if err != nil {
130142 return nil , nil , err
131143 }
144+ o .Path = path
132145
133146 if ! o .Mode .IsRegular () {
134147 return nil , nil , fmt .Errorf ("unsupported file type: %s" , o .Path )
135148 }
136149 if o .MakeParents {
137- if err := os .MkdirAll (filepath .Dir (o . Path ), 0755 ); err != nil {
150+ if err := os .MkdirAll (filepath .Dir (path ), 0755 ); err != nil {
138151 return nil , nil , err
139152 }
140153 }
@@ -221,18 +234,13 @@ func createHardLink(o *CreateOptions) error {
221234 return err
222235}
223236
224- func setValidPath (o * CreateOptions ) error {
225- if o .Root == "" {
226- o .Root = "/"
227- }
228- if o .Root != "/" {
229- o .Root = filepath .Clean (o .Root ) + "/"
230- }
231- o .Path = filepath .Clean (filepath .Join (o .Root , o .Path ))
232- if ! strings .HasPrefix (o .Path , o .Root ) {
233- return fmt .Errorf ("cannot create path %s outside of root %s" , o .Path , o .Root )
237+ // absPath requires root to be a clean path that ends in "/".
238+ func absPath (root , relPath string ) (string , error ) {
239+ path := filepath .Clean (filepath .Join (root , relPath ))
240+ if ! strings .HasPrefix (path , root ) {
241+ return "" , fmt .Errorf ("cannot create path %s outside of root %s" , path , root )
234242 }
235- return nil
243+ return path , nil
236244}
237245
238246// readerProxy implements the io.Reader interface proxying the calls to its
0 commit comments