You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PackParser.java 54KB

maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
ObjectIdOwnerMap: More lightweight map for ObjectIds OwnerMap is about 200 ms faster than SubclassMap, more friendly to the GC, and uses less storage: testing the "Counting objects" part of PackWriter on 1886362 objects: ObjectIdSubclassMap: load factor 50% table: 4194304 (wasted 2307942) ms spent 36998 36009 34795 34703 34941 35070 34284 34511 34638 34256 ms avg 34800 (last 9 runs) ObjectIdOwnerMap: load factor 100% table: 2097152 (wasted 210790) directory: 1024 ms spent 36842 35112 34922 34703 34580 34782 34165 34662 34314 34140 ms avg 34597 (last 9 runs) The major difference with OwnerMap is entries must extend from ObjectIdOwnerMap.Entry, where the OwnerMap has injected its own private "next" field into each object. This allows the OwnerMap to use a singly linked list for chaining collisions within a bucket. By putting collisions in a linked list, we gain the entire table back for the SHA-1 bits to index their own "private" slot. Unfortunately this means that each object can appear in at most ONE OwnerMap, as there is only one "next" field within the object instance to thread into the map. For types that are very object map heavy like RevWalk (entity RevObject) and PackWriter (entity ObjectToPack) this is sufficient, these entity types are only put into one map by their container. By introducing a new map type, we don't break existing applications that might be trying to use ObjectIdSubclassMap to track RevCommits they obtained from a RevWalk. The OwnerMap uses less memory. Each object uses 1 reference more (so we're up 1,886,362 references), but the table is 1/2 the size (2^20 rather than 2^21). The table itself wastes only 210,790 slots, rather than 2,307,942. So OwnerMap is wasting 200k fewer references. OwnerMap is more friendly to the GC, because it hardly ever generates garbage. As the map reaches its 100% load factor target, it doubles in size by allocating additional segment arrays of 2048 entries. (So the first grow allocates 1 segment, second 2 segments, third 4 segments, etc.) These segments are hooked into the pre-allocated directory of 1024 spaces. This permits the map to grow to 2 million objects before the directory itself has to grow. By using segments of 2048 entries, we are asking the GC to acquire 8,204 bytes in a 32 bit JVM. This is easier to satisfy then 2,307,942 bytes (for the 512k table that is just an intermediate step in the SubclassMap). By reusing the previously allocated segments (they are re-hashed in-place) we don't release any memory during a table grow. When the directory grows, it does so by discarding the old one and using one that is 4x larger (so the directory goes to 4096 entries on its first grow). A directory of size 4096 can handle up to 8 millon objects. The second directory grow (16384) goes to 33 million objects. At that point we're starting to really push the limits of the JVM heap, but at least its many small arrays. Previously SubclassMap would need a table of 67108864 entries to handle that object count, which needs a single contiguous allocation of 256 MiB. That's hard to come by in a 32 bit JVM. Instead OwnerMap uses 8192 arrays of about 8 KiB each. This is much easier to fit into a fragmented heap. Change-Id: Ia4acf5cfbf7e9b71bc7faa0db9060f6a969c0c50 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
ObjectIdOwnerMap: More lightweight map for ObjectIds OwnerMap is about 200 ms faster than SubclassMap, more friendly to the GC, and uses less storage: testing the "Counting objects" part of PackWriter on 1886362 objects: ObjectIdSubclassMap: load factor 50% table: 4194304 (wasted 2307942) ms spent 36998 36009 34795 34703 34941 35070 34284 34511 34638 34256 ms avg 34800 (last 9 runs) ObjectIdOwnerMap: load factor 100% table: 2097152 (wasted 210790) directory: 1024 ms spent 36842 35112 34922 34703 34580 34782 34165 34662 34314 34140 ms avg 34597 (last 9 runs) The major difference with OwnerMap is entries must extend from ObjectIdOwnerMap.Entry, where the OwnerMap has injected its own private "next" field into each object. This allows the OwnerMap to use a singly linked list for chaining collisions within a bucket. By putting collisions in a linked list, we gain the entire table back for the SHA-1 bits to index their own "private" slot. Unfortunately this means that each object can appear in at most ONE OwnerMap, as there is only one "next" field within the object instance to thread into the map. For types that are very object map heavy like RevWalk (entity RevObject) and PackWriter (entity ObjectToPack) this is sufficient, these entity types are only put into one map by their container. By introducing a new map type, we don't break existing applications that might be trying to use ObjectIdSubclassMap to track RevCommits they obtained from a RevWalk. The OwnerMap uses less memory. Each object uses 1 reference more (so we're up 1,886,362 references), but the table is 1/2 the size (2^20 rather than 2^21). The table itself wastes only 210,790 slots, rather than 2,307,942. So OwnerMap is wasting 200k fewer references. OwnerMap is more friendly to the GC, because it hardly ever generates garbage. As the map reaches its 100% load factor target, it doubles in size by allocating additional segment arrays of 2048 entries. (So the first grow allocates 1 segment, second 2 segments, third 4 segments, etc.) These segments are hooked into the pre-allocated directory of 1024 spaces. This permits the map to grow to 2 million objects before the directory itself has to grow. By using segments of 2048 entries, we are asking the GC to acquire 8,204 bytes in a 32 bit JVM. This is easier to satisfy then 2,307,942 bytes (for the 512k table that is just an intermediate step in the SubclassMap). By reusing the previously allocated segments (they are re-hashed in-place) we don't release any memory during a table grow. When the directory grows, it does so by discarding the old one and using one that is 4x larger (so the directory goes to 4096 entries on its first grow). A directory of size 4096 can handle up to 8 millon objects. The second directory grow (16384) goes to 33 million objects. At that point we're starting to really push the limits of the JVM heap, but at least its many small arrays. Previously SubclassMap would need a table of 67108864 entries to handle that object count, which needs a single contiguous allocation of 256 MiB. That's hard to come by in a 32 bit JVM. Instead OwnerMap uses 8192 arrays of about 8 KiB each. This is much easier to fit into a fragmented heap. Change-Id: Ia4acf5cfbf7e9b71bc7faa0db9060f6a969c0c50 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
Store Git on any DHT jgit.storage.dht is a storage provider implementation for JGit that permits storing the Git repository in a distributed hashtable, NoSQL system, or other database. The actual underlying storage system is undefined, and can be plugged in by implementing 7 small interfaces: * Database * RepositoryIndexTable * RepositoryTable * RefTable * ChunkTable * ObjectIndexTable * WriteBuffer The storage provider interface tries to assume very little about the underlying storage system, and requires only three key features: * key -> value lookup (a hashtable is suitable) * atomic updates on single rows * asynchronous operations (Java's ExecutorService is easy to use) Most NoSQL database products offer all 3 of these features in their clients, and so does any decent network based cache system like the open source memcache product. Relying only on key equality for data retrevial makes it simple for the storage engine to distribute across multiple machines. Traditional SQL systems could also be used with a JDBC based spi implementation. Before submitting this change I have implemented six storage systems for the spi layer: * Apache HBase[1] * Apache Cassandra[2] * Google Bigtable[3] * an in-memory implementation for unit testing * a JDBC implementation for SQL * a generic cache provider that can ride on top of memcache All six systems came in with an spi layer around 1000 lines of code to implement the above 7 interfaces. This is a huge reduction in size compared to prior attempts to implement a new JGit storage layer. As this package shows, a complete JGit storage implementation is more than 17,000 lines of fairly complex code. A simple cache is provided in storage.dht.spi.cache. Implementers can use CacheDatabase to wrap any other type of Database and perform fast reads against a network based cache service, such as the open source memcached[4]. An implementation of CacheService must be provided to glue this spi onto the network cache. [1] https://github.com/spearce/jgit_hbase [2] https://github.com/spearce/jgit_cassandra [3] http://labs.google.com/papers/bigtable.html [4] http://memcached.org/ Change-Id: I0aa4072781f5ccc019ca421c036adff2c40c4295 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
Store Git on any DHT jgit.storage.dht is a storage provider implementation for JGit that permits storing the Git repository in a distributed hashtable, NoSQL system, or other database. The actual underlying storage system is undefined, and can be plugged in by implementing 7 small interfaces: * Database * RepositoryIndexTable * RepositoryTable * RefTable * ChunkTable * ObjectIndexTable * WriteBuffer The storage provider interface tries to assume very little about the underlying storage system, and requires only three key features: * key -> value lookup (a hashtable is suitable) * atomic updates on single rows * asynchronous operations (Java's ExecutorService is easy to use) Most NoSQL database products offer all 3 of these features in their clients, and so does any decent network based cache system like the open source memcache product. Relying only on key equality for data retrevial makes it simple for the storage engine to distribute across multiple machines. Traditional SQL systems could also be used with a JDBC based spi implementation. Before submitting this change I have implemented six storage systems for the spi layer: * Apache HBase[1] * Apache Cassandra[2] * Google Bigtable[3] * an in-memory implementation for unit testing * a JDBC implementation for SQL * a generic cache provider that can ride on top of memcache All six systems came in with an spi layer around 1000 lines of code to implement the above 7 interfaces. This is a huge reduction in size compared to prior attempts to implement a new JGit storage layer. As this package shows, a complete JGit storage implementation is more than 17,000 lines of fairly complex code. A simple cache is provided in storage.dht.spi.cache. Implementers can use CacheDatabase to wrap any other type of Database and perform fast reads against a network based cache service, such as the open source memcached[4]. An implementation of CacheService must be provided to glue this spi onto the network cache. [1] https://github.com/spearce/jgit_hbase [2] https://github.com/spearce/jgit_cassandra [3] http://labs.google.com/papers/bigtable.html [4] http://memcached.org/ Change-Id: I0aa4072781f5ccc019ca421c036adff2c40c4295 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
maxObjectSizeLimit for receive-pack. ReceivePack (and PackParser) can be configured with the maxObjectSizeLimit in order to prevent users from pushing too large objects to Git. The limit check is applied to all object types although it is most likely that a BLOB will exceed the limit. In all cases the size of the object header is excluded from the object size which is checked against the limit as this is the size of which a BLOB object would take in the working tree when checked out as a file. When an object exceeds the maxObjectSizeLimit the receive-pack will abort immediately. Delta objects (both offset and ref delta) are also checked against the limit. However, for delta objects we will first check the size of the inflated delta block against the maxObjectSizeLimit and abort immediately if it exceeds the limit. In this case we even do not know the exact size of the resolved delta object but we assume it will be larger than the given maxObjectSizeLimit as delta is generally only chosen if the delta can copy more data from the base object than the delta needs to insert or needs to represent the copy ranges. Aborting early, in this case, avoids unnecessary inflating of the (huge) delta block. Unfortunately, it is too expensive (especially for a large delta) to compute SHA-1 of an object that causes the receive-pack to abort. This would decrease the value of this feature whose main purpose is to protect server resources from users pushing huge objects. Therefore we don't report the SHA-1 in the error message. Change-Id: I177ef24553faacda444ed5895e40ac8925ca0d1e Signed-off-by: Sasa Zivkov <sasa.zivkov@sap.com> Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
12 years ago
Store Git on any DHT jgit.storage.dht is a storage provider implementation for JGit that permits storing the Git repository in a distributed hashtable, NoSQL system, or other database. The actual underlying storage system is undefined, and can be plugged in by implementing 7 small interfaces: * Database * RepositoryIndexTable * RepositoryTable * RefTable * ChunkTable * ObjectIndexTable * WriteBuffer The storage provider interface tries to assume very little about the underlying storage system, and requires only three key features: * key -> value lookup (a hashtable is suitable) * atomic updates on single rows * asynchronous operations (Java's ExecutorService is easy to use) Most NoSQL database products offer all 3 of these features in their clients, and so does any decent network based cache system like the open source memcache product. Relying only on key equality for data retrevial makes it simple for the storage engine to distribute across multiple machines. Traditional SQL systems could also be used with a JDBC based spi implementation. Before submitting this change I have implemented six storage systems for the spi layer: * Apache HBase[1] * Apache Cassandra[2] * Google Bigtable[3] * an in-memory implementation for unit testing * a JDBC implementation for SQL * a generic cache provider that can ride on top of memcache All six systems came in with an spi layer around 1000 lines of code to implement the above 7 interfaces. This is a huge reduction in size compared to prior attempts to implement a new JGit storage layer. As this package shows, a complete JGit storage implementation is more than 17,000 lines of fairly complex code. A simple cache is provided in storage.dht.spi.cache. Implementers can use CacheDatabase to wrap any other type of Database and perform fast reads against a network based cache service, such as the open source memcached[4]. An implementation of CacheService must be provided to glue this spi onto the network cache. [1] https://github.com/spearce/jgit_hbase [2] https://github.com/spearce/jgit_cassandra [3] http://labs.google.com/papers/bigtable.html [4] http://memcached.org/ Change-Id: I0aa4072781f5ccc019ca421c036adff2c40c4295 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
Store Git on any DHT jgit.storage.dht is a storage provider implementation for JGit that permits storing the Git repository in a distributed hashtable, NoSQL system, or other database. The actual underlying storage system is undefined, and can be plugged in by implementing 7 small interfaces: * Database * RepositoryIndexTable * RepositoryTable * RefTable * ChunkTable * ObjectIndexTable * WriteBuffer The storage provider interface tries to assume very little about the underlying storage system, and requires only three key features: * key -> value lookup (a hashtable is suitable) * atomic updates on single rows * asynchronous operations (Java's ExecutorService is easy to use) Most NoSQL database products offer all 3 of these features in their clients, and so does any decent network based cache system like the open source memcache product. Relying only on key equality for data retrevial makes it simple for the storage engine to distribute across multiple machines. Traditional SQL systems could also be used with a JDBC based spi implementation. Before submitting this change I have implemented six storage systems for the spi layer: * Apache HBase[1] * Apache Cassandra[2] * Google Bigtable[3] * an in-memory implementation for unit testing * a JDBC implementation for SQL * a generic cache provider that can ride on top of memcache All six systems came in with an spi layer around 1000 lines of code to implement the above 7 interfaces. This is a huge reduction in size compared to prior attempts to implement a new JGit storage layer. As this package shows, a complete JGit storage implementation is more than 17,000 lines of fairly complex code. A simple cache is provided in storage.dht.spi.cache. Implementers can use CacheDatabase to wrap any other type of Database and perform fast reads against a network based cache service, such as the open source memcached[4]. An implementation of CacheService must be provided to glue this spi onto the network cache. [1] https://github.com/spearce/jgit_hbase [2] https://github.com/spearce/jgit_cassandra [3] http://labs.google.com/papers/bigtable.html [4] http://memcached.org/ Change-Id: I0aa4072781f5ccc019ca421c036adff2c40c4295 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
Store Git on any DHT jgit.storage.dht is a storage provider implementation for JGit that permits storing the Git repository in a distributed hashtable, NoSQL system, or other database. The actual underlying storage system is undefined, and can be plugged in by implementing 7 small interfaces: * Database * RepositoryIndexTable * RepositoryTable * RefTable * ChunkTable * ObjectIndexTable * WriteBuffer The storage provider interface tries to assume very little about the underlying storage system, and requires only three key features: * key -> value lookup (a hashtable is suitable) * atomic updates on single rows * asynchronous operations (Java's ExecutorService is easy to use) Most NoSQL database products offer all 3 of these features in their clients, and so does any decent network based cache system like the open source memcache product. Relying only on key equality for data retrevial makes it simple for the storage engine to distribute across multiple machines. Traditional SQL systems could also be used with a JDBC based spi implementation. Before submitting this change I have implemented six storage systems for the spi layer: * Apache HBase[1] * Apache Cassandra[2] * Google Bigtable[3] * an in-memory implementation for unit testing * a JDBC implementation for SQL * a generic cache provider that can ride on top of memcache All six systems came in with an spi layer around 1000 lines of code to implement the above 7 interfaces. This is a huge reduction in size compared to prior attempts to implement a new JGit storage layer. As this package shows, a complete JGit storage implementation is more than 17,000 lines of fairly complex code. A simple cache is provided in storage.dht.spi.cache. Implementers can use CacheDatabase to wrap any other type of Database and perform fast reads against a network based cache service, such as the open source memcached[4]. An implementation of CacheService must be provided to glue this spi onto the network cache. [1] https://github.com/spearce/jgit_hbase [2] https://github.com/spearce/jgit_cassandra [3] http://labs.google.com/papers/bigtable.html [4] http://memcached.org/ Change-Id: I0aa4072781f5ccc019ca421c036adff2c40c4295 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
Store Git on any DHT jgit.storage.dht is a storage provider implementation for JGit that permits storing the Git repository in a distributed hashtable, NoSQL system, or other database. The actual underlying storage system is undefined, and can be plugged in by implementing 7 small interfaces: * Database * RepositoryIndexTable * RepositoryTable * RefTable * ChunkTable * ObjectIndexTable * WriteBuffer The storage provider interface tries to assume very little about the underlying storage system, and requires only three key features: * key -> value lookup (a hashtable is suitable) * atomic updates on single rows * asynchronous operations (Java's ExecutorService is easy to use) Most NoSQL database products offer all 3 of these features in their clients, and so does any decent network based cache system like the open source memcache product. Relying only on key equality for data retrevial makes it simple for the storage engine to distribute across multiple machines. Traditional SQL systems could also be used with a JDBC based spi implementation. Before submitting this change I have implemented six storage systems for the spi layer: * Apache HBase[1] * Apache Cassandra[2] * Google Bigtable[3] * an in-memory implementation for unit testing * a JDBC implementation for SQL * a generic cache provider that can ride on top of memcache All six systems came in with an spi layer around 1000 lines of code to implement the above 7 interfaces. This is a huge reduction in size compared to prior attempts to implement a new JGit storage layer. As this package shows, a complete JGit storage implementation is more than 17,000 lines of fairly complex code. A simple cache is provided in storage.dht.spi.cache. Implementers can use CacheDatabase to wrap any other type of Database and perform fast reads against a network based cache service, such as the open source memcached[4]. An implementation of CacheService must be provided to glue this spi onto the network cache. [1] https://github.com/spearce/jgit_hbase [2] https://github.com/spearce/jgit_cassandra [3] http://labs.google.com/papers/bigtable.html [4] http://memcached.org/ Change-Id: I0aa4072781f5ccc019ca421c036adff2c40c4295 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
Store Git on any DHT jgit.storage.dht is a storage provider implementation for JGit that permits storing the Git repository in a distributed hashtable, NoSQL system, or other database. The actual underlying storage system is undefined, and can be plugged in by implementing 7 small interfaces: * Database * RepositoryIndexTable * RepositoryTable * RefTable * ChunkTable * ObjectIndexTable * WriteBuffer The storage provider interface tries to assume very little about the underlying storage system, and requires only three key features: * key -> value lookup (a hashtable is suitable) * atomic updates on single rows * asynchronous operations (Java's ExecutorService is easy to use) Most NoSQL database products offer all 3 of these features in their clients, and so does any decent network based cache system like the open source memcache product. Relying only on key equality for data retrevial makes it simple for the storage engine to distribute across multiple machines. Traditional SQL systems could also be used with a JDBC based spi implementation. Before submitting this change I have implemented six storage systems for the spi layer: * Apache HBase[1] * Apache Cassandra[2] * Google Bigtable[3] * an in-memory implementation for unit testing * a JDBC implementation for SQL * a generic cache provider that can ride on top of memcache All six systems came in with an spi layer around 1000 lines of code to implement the above 7 interfaces. This is a huge reduction in size compared to prior attempts to implement a new JGit storage layer. As this package shows, a complete JGit storage implementation is more than 17,000 lines of fairly complex code. A simple cache is provided in storage.dht.spi.cache. Implementers can use CacheDatabase to wrap any other type of Database and perform fast reads against a network based cache service, such as the open source memcached[4]. An implementation of CacheService must be provided to glue this spi onto the network cache. [1] https://github.com/spearce/jgit_hbase [2] https://github.com/spearce/jgit_cassandra [3] http://labs.google.com/papers/bigtable.html [4] http://memcached.org/ Change-Id: I0aa4072781f5ccc019ca421c036adff2c40c4295 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
Store Git on any DHT jgit.storage.dht is a storage provider implementation for JGit that permits storing the Git repository in a distributed hashtable, NoSQL system, or other database. The actual underlying storage system is undefined, and can be plugged in by implementing 7 small interfaces: * Database * RepositoryIndexTable * RepositoryTable * RefTable * ChunkTable * ObjectIndexTable * WriteBuffer The storage provider interface tries to assume very little about the underlying storage system, and requires only three key features: * key -> value lookup (a hashtable is suitable) * atomic updates on single rows * asynchronous operations (Java's ExecutorService is easy to use) Most NoSQL database products offer all 3 of these features in their clients, and so does any decent network based cache system like the open source memcache product. Relying only on key equality for data retrevial makes it simple for the storage engine to distribute across multiple machines. Traditional SQL systems could also be used with a JDBC based spi implementation. Before submitting this change I have implemented six storage systems for the spi layer: * Apache HBase[1] * Apache Cassandra[2] * Google Bigtable[3] * an in-memory implementation for unit testing * a JDBC implementation for SQL * a generic cache provider that can ride on top of memcache All six systems came in with an spi layer around 1000 lines of code to implement the above 7 interfaces. This is a huge reduction in size compared to prior attempts to implement a new JGit storage layer. As this package shows, a complete JGit storage implementation is more than 17,000 lines of fairly complex code. A simple cache is provided in storage.dht.spi.cache. Implementers can use CacheDatabase to wrap any other type of Database and perform fast reads against a network based cache service, such as the open source memcached[4]. An implementation of CacheService must be provided to glue this spi onto the network cache. [1] https://github.com/spearce/jgit_hbase [2] https://github.com/spearce/jgit_cassandra [3] http://labs.google.com/papers/bigtable.html [4] http://memcached.org/ Change-Id: I0aa4072781f5ccc019ca421c036adff2c40c4295 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
Store Git on any DHT jgit.storage.dht is a storage provider implementation for JGit that permits storing the Git repository in a distributed hashtable, NoSQL system, or other database. The actual underlying storage system is undefined, and can be plugged in by implementing 7 small interfaces: * Database * RepositoryIndexTable * RepositoryTable * RefTable * ChunkTable * ObjectIndexTable * WriteBuffer The storage provider interface tries to assume very little about the underlying storage system, and requires only three key features: * key -> value lookup (a hashtable is suitable) * atomic updates on single rows * asynchronous operations (Java's ExecutorService is easy to use) Most NoSQL database products offer all 3 of these features in their clients, and so does any decent network based cache system like the open source memcache product. Relying only on key equality for data retrevial makes it simple for the storage engine to distribute across multiple machines. Traditional SQL systems could also be used with a JDBC based spi implementation. Before submitting this change I have implemented six storage systems for the spi layer: * Apache HBase[1] * Apache Cassandra[2] * Google Bigtable[3] * an in-memory implementation for unit testing * a JDBC implementation for SQL * a generic cache provider that can ride on top of memcache All six systems came in with an spi layer around 1000 lines of code to implement the above 7 interfaces. This is a huge reduction in size compared to prior attempts to implement a new JGit storage layer. As this package shows, a complete JGit storage implementation is more than 17,000 lines of fairly complex code. A simple cache is provided in storage.dht.spi.cache. Implementers can use CacheDatabase to wrap any other type of Database and perform fast reads against a network based cache service, such as the open source memcached[4]. An implementation of CacheService must be provided to glue this spi onto the network cache. [1] https://github.com/spearce/jgit_hbase [2] https://github.com/spearce/jgit_cassandra [3] http://labs.google.com/papers/bigtable.html [4] http://memcached.org/ Change-Id: I0aa4072781f5ccc019ca421c036adff2c40c4295 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
ObjectIdOwnerMap: More lightweight map for ObjectIds OwnerMap is about 200 ms faster than SubclassMap, more friendly to the GC, and uses less storage: testing the "Counting objects" part of PackWriter on 1886362 objects: ObjectIdSubclassMap: load factor 50% table: 4194304 (wasted 2307942) ms spent 36998 36009 34795 34703 34941 35070 34284 34511 34638 34256 ms avg 34800 (last 9 runs) ObjectIdOwnerMap: load factor 100% table: 2097152 (wasted 210790) directory: 1024 ms spent 36842 35112 34922 34703 34580 34782 34165 34662 34314 34140 ms avg 34597 (last 9 runs) The major difference with OwnerMap is entries must extend from ObjectIdOwnerMap.Entry, where the OwnerMap has injected its own private "next" field into each object. This allows the OwnerMap to use a singly linked list for chaining collisions within a bucket. By putting collisions in a linked list, we gain the entire table back for the SHA-1 bits to index their own "private" slot. Unfortunately this means that each object can appear in at most ONE OwnerMap, as there is only one "next" field within the object instance to thread into the map. For types that are very object map heavy like RevWalk (entity RevObject) and PackWriter (entity ObjectToPack) this is sufficient, these entity types are only put into one map by their container. By introducing a new map type, we don't break existing applications that might be trying to use ObjectIdSubclassMap to track RevCommits they obtained from a RevWalk. The OwnerMap uses less memory. Each object uses 1 reference more (so we're up 1,886,362 references), but the table is 1/2 the size (2^20 rather than 2^21). The table itself wastes only 210,790 slots, rather than 2,307,942. So OwnerMap is wasting 200k fewer references. OwnerMap is more friendly to the GC, because it hardly ever generates garbage. As the map reaches its 100% load factor target, it doubles in size by allocating additional segment arrays of 2048 entries. (So the first grow allocates 1 segment, second 2 segments, third 4 segments, etc.) These segments are hooked into the pre-allocated directory of 1024 spaces. This permits the map to grow to 2 million objects before the directory itself has to grow. By using segments of 2048 entries, we are asking the GC to acquire 8,204 bytes in a 32 bit JVM. This is easier to satisfy then 2,307,942 bytes (for the 512k table that is just an intermediate step in the SubclassMap). By reusing the previously allocated segments (they are re-hashed in-place) we don't release any memory during a table grow. When the directory grows, it does so by discarding the old one and using one that is 4x larger (so the directory goes to 4096 entries on its first grow). A directory of size 4096 can handle up to 8 millon objects. The second directory grow (16384) goes to 33 million objects. At that point we're starting to really push the limits of the JVM heap, but at least its many small arrays. Previously SubclassMap would need a table of 67108864 entries to handle that object count, which needs a single contiguous allocation of 256 MiB. That's hard to come by in a 32 bit JVM. Instead OwnerMap uses 8192 arrays of about 8 KiB each. This is much easier to fit into a fragmented heap. Change-Id: Ia4acf5cfbf7e9b71bc7faa0db9060f6a969c0c50 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854
  1. /*
  2. * Copyright (C) 2008-2011, Google Inc.
  3. * Copyright (C) 2007-2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.transport;
  46. import java.io.EOFException;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.security.MessageDigest;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.Arrays;
  53. import java.util.Comparator;
  54. import java.util.List;
  55. import java.util.concurrent.TimeUnit;
  56. import java.util.zip.DataFormatException;
  57. import java.util.zip.Inflater;
  58. import org.eclipse.jgit.errors.CorruptObjectException;
  59. import org.eclipse.jgit.errors.MissingObjectException;
  60. import org.eclipse.jgit.errors.TooLargeObjectInPackException;
  61. import org.eclipse.jgit.internal.JGitText;
  62. import org.eclipse.jgit.internal.storage.file.PackLock;
  63. import org.eclipse.jgit.internal.storage.pack.BinaryDelta;
  64. import org.eclipse.jgit.lib.AnyObjectId;
  65. import org.eclipse.jgit.lib.BatchingProgressMonitor;
  66. import org.eclipse.jgit.lib.BlobObjectChecker;
  67. import org.eclipse.jgit.lib.Constants;
  68. import org.eclipse.jgit.lib.InflaterCache;
  69. import org.eclipse.jgit.lib.MutableObjectId;
  70. import org.eclipse.jgit.lib.NullProgressMonitor;
  71. import org.eclipse.jgit.lib.ObjectChecker;
  72. import org.eclipse.jgit.lib.ObjectDatabase;
  73. import org.eclipse.jgit.lib.ObjectId;
  74. import org.eclipse.jgit.lib.ObjectIdOwnerMap;
  75. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  76. import org.eclipse.jgit.lib.ObjectLoader;
  77. import org.eclipse.jgit.lib.ObjectReader;
  78. import org.eclipse.jgit.lib.ObjectStream;
  79. import org.eclipse.jgit.lib.ProgressMonitor;
  80. import org.eclipse.jgit.util.BlockList;
  81. import org.eclipse.jgit.util.IO;
  82. import org.eclipse.jgit.util.LongMap;
  83. import org.eclipse.jgit.util.NB;
  84. import org.eclipse.jgit.util.sha1.SHA1;
  85. /**
  86. * Parses a pack stream and imports it for an
  87. * {@link org.eclipse.jgit.lib.ObjectInserter}.
  88. * <p>
  89. * Applications can acquire an instance of a parser from ObjectInserter's
  90. * {@link org.eclipse.jgit.lib.ObjectInserter#newPackParser(InputStream)}
  91. * method.
  92. * <p>
  93. * Implementations of {@link org.eclipse.jgit.lib.ObjectInserter} should
  94. * subclass this type and provide their own logic for the various {@code on*()}
  95. * event methods declared to be abstract.
  96. */
  97. public abstract class PackParser {
  98. /** Size of the internal stream buffer. */
  99. private static final int BUFFER_SIZE = 8192;
  100. /** Location data is being obtained from. */
  101. public static enum Source {
  102. /** Data is read from the incoming stream. */
  103. INPUT,
  104. /** Data is read back from the database's buffers. */
  105. DATABASE;
  106. }
  107. /** Object database used for loading existing objects. */
  108. private final ObjectDatabase objectDatabase;
  109. private InflaterStream inflater;
  110. private byte[] tempBuffer;
  111. private byte[] hdrBuf;
  112. private final SHA1 objectHasher = SHA1.newInstance();
  113. private final MutableObjectId tempObjectId;
  114. private InputStream in;
  115. byte[] buf;
  116. /** Position in the input stream of {@code buf[0]}. */
  117. private long bBase;
  118. private int bOffset;
  119. int bAvail;
  120. private ObjectChecker objCheck;
  121. private boolean allowThin;
  122. private boolean checkObjectCollisions;
  123. private boolean needBaseObjectIds;
  124. private boolean checkEofAfterPackFooter;
  125. private boolean expectDataAfterPackFooter;
  126. private long expectedObjectCount;
  127. private PackedObjectInfo[] entries;
  128. /**
  129. * Every object contained within the incoming pack.
  130. * <p>
  131. * This is a subset of {@link #entries}, as thin packs can add additional
  132. * objects to {@code entries} by copying already existing objects from the
  133. * repository onto the end of the thin pack to make it self-contained.
  134. */
  135. private ObjectIdSubclassMap<ObjectId> newObjectIds;
  136. private int deltaCount;
  137. private int entryCount;
  138. private ObjectIdOwnerMap<DeltaChain> baseById;
  139. /**
  140. * Objects referenced by their name from deltas, that aren't in this pack.
  141. * <p>
  142. * This is the set of objects that were copied onto the end of this pack to
  143. * make it complete. These objects were not transmitted by the remote peer,
  144. * but instead were assumed to already exist in the local repository.
  145. */
  146. private ObjectIdSubclassMap<ObjectId> baseObjectIds;
  147. private LongMap<UnresolvedDelta> baseByPos;
  148. /** Objects need to be double-checked for collision after indexing. */
  149. private BlockList<PackedObjectInfo> collisionCheckObjs;
  150. private MessageDigest packDigest;
  151. private ObjectReader readCurs;
  152. /** Message to protect the pack data from garbage collection. */
  153. private String lockMessage;
  154. /** Git object size limit */
  155. private long maxObjectSizeLimit;
  156. private final ReceivedPackStatistics.Builder stats =
  157. new ReceivedPackStatistics.Builder();
  158. /**
  159. * Initialize a pack parser.
  160. *
  161. * @param odb
  162. * database the parser will write its objects into.
  163. * @param src
  164. * the stream the parser will read.
  165. */
  166. protected PackParser(ObjectDatabase odb, InputStream src) {
  167. objectDatabase = odb.newCachedDatabase();
  168. in = src;
  169. inflater = new InflaterStream();
  170. readCurs = objectDatabase.newReader();
  171. buf = new byte[BUFFER_SIZE];
  172. tempBuffer = new byte[BUFFER_SIZE];
  173. hdrBuf = new byte[64];
  174. tempObjectId = new MutableObjectId();
  175. packDigest = Constants.newMessageDigest();
  176. checkObjectCollisions = true;
  177. }
  178. /**
  179. * Whether a thin pack (missing base objects) is permitted.
  180. *
  181. * @return {@code true} if a thin pack (missing base objects) is permitted.
  182. */
  183. public boolean isAllowThin() {
  184. return allowThin;
  185. }
  186. /**
  187. * Configure this index pack instance to allow a thin pack.
  188. * <p>
  189. * Thin packs are sometimes used during network transfers to allow a delta
  190. * to be sent without a base object. Such packs are not permitted on disk.
  191. *
  192. * @param allow
  193. * true to enable a thin pack.
  194. */
  195. public void setAllowThin(boolean allow) {
  196. allowThin = allow;
  197. }
  198. /**
  199. * Whether received objects are verified to prevent collisions.
  200. *
  201. * @return if true received objects are verified to prevent collisions.
  202. * @since 4.1
  203. */
  204. protected boolean isCheckObjectCollisions() {
  205. return checkObjectCollisions;
  206. }
  207. /**
  208. * Enable checking for collisions with existing objects.
  209. * <p>
  210. * By default PackParser looks for each received object in the repository.
  211. * If the object already exists, the existing object is compared
  212. * byte-for-byte with the newly received copy to ensure they are identical.
  213. * The receive is aborted with an exception if any byte differs. This check
  214. * is necessary to prevent an evil attacker from supplying a replacement
  215. * object into this repository in the event that a discovery enabling SHA-1
  216. * collisions is made.
  217. * <p>
  218. * This check may be very costly to perform, and some repositories may have
  219. * other ways to segregate newly received object data. The check is enabled
  220. * by default, but can be explicitly disabled if the implementation can
  221. * provide the same guarantee, or is willing to accept the risks associated
  222. * with bypassing the check.
  223. *
  224. * @param check
  225. * true to enable collision checking (strongly encouraged).
  226. * @since 4.1
  227. */
  228. protected void setCheckObjectCollisions(boolean check) {
  229. checkObjectCollisions = check;
  230. }
  231. /**
  232. * Configure this index pack instance to keep track of new objects.
  233. * <p>
  234. * By default an index pack doesn't save the new objects that were created
  235. * when it was instantiated. Setting this flag to {@code true} allows the
  236. * caller to use {@link #getNewObjectIds()} to retrieve that list.
  237. *
  238. * @param b
  239. * {@code true} to enable keeping track of new objects.
  240. */
  241. public void setNeedNewObjectIds(boolean b) {
  242. if (b)
  243. newObjectIds = new ObjectIdSubclassMap<>();
  244. else
  245. newObjectIds = null;
  246. }
  247. private boolean needNewObjectIds() {
  248. return newObjectIds != null;
  249. }
  250. /**
  251. * Configure this index pack instance to keep track of the objects assumed
  252. * for delta bases.
  253. * <p>
  254. * By default an index pack doesn't save the objects that were used as delta
  255. * bases. Setting this flag to {@code true} will allow the caller to use
  256. * {@link #getBaseObjectIds()} to retrieve that list.
  257. *
  258. * @param b
  259. * {@code true} to enable keeping track of delta bases.
  260. */
  261. public void setNeedBaseObjectIds(boolean b) {
  262. this.needBaseObjectIds = b;
  263. }
  264. /**
  265. * Whether the EOF should be read from the input after the footer.
  266. *
  267. * @return true if the EOF should be read from the input after the footer.
  268. */
  269. public boolean isCheckEofAfterPackFooter() {
  270. return checkEofAfterPackFooter;
  271. }
  272. /**
  273. * Ensure EOF is read from the input stream after the footer.
  274. *
  275. * @param b
  276. * true if the EOF should be read; false if it is not checked.
  277. */
  278. public void setCheckEofAfterPackFooter(boolean b) {
  279. checkEofAfterPackFooter = b;
  280. }
  281. /**
  282. * Whether there is data expected after the pack footer.
  283. *
  284. * @return true if there is data expected after the pack footer.
  285. */
  286. public boolean isExpectDataAfterPackFooter() {
  287. return expectDataAfterPackFooter;
  288. }
  289. /**
  290. * Set if there is additional data in InputStream after pack.
  291. *
  292. * @param e
  293. * true if there is additional data in InputStream after pack.
  294. * This requires the InputStream to support the mark and reset
  295. * functions.
  296. */
  297. public void setExpectDataAfterPackFooter(boolean e) {
  298. expectDataAfterPackFooter = e;
  299. }
  300. /**
  301. * Get the new objects that were sent by the user
  302. *
  303. * @return the new objects that were sent by the user
  304. */
  305. public ObjectIdSubclassMap<ObjectId> getNewObjectIds() {
  306. if (newObjectIds != null)
  307. return newObjectIds;
  308. return new ObjectIdSubclassMap<>();
  309. }
  310. /**
  311. * Get set of objects the incoming pack assumed for delta purposes
  312. *
  313. * @return set of objects the incoming pack assumed for delta purposes
  314. */
  315. public ObjectIdSubclassMap<ObjectId> getBaseObjectIds() {
  316. if (baseObjectIds != null)
  317. return baseObjectIds;
  318. return new ObjectIdSubclassMap<>();
  319. }
  320. /**
  321. * Configure the checker used to validate received objects.
  322. * <p>
  323. * Usually object checking isn't necessary, as Git implementations only
  324. * create valid objects in pack files. However, additional checking may be
  325. * useful if processing data from an untrusted source.
  326. *
  327. * @param oc
  328. * the checker instance; null to disable object checking.
  329. */
  330. public void setObjectChecker(ObjectChecker oc) {
  331. objCheck = oc;
  332. }
  333. /**
  334. * Configure the checker used to validate received objects.
  335. * <p>
  336. * Usually object checking isn't necessary, as Git implementations only
  337. * create valid objects in pack files. However, additional checking may be
  338. * useful if processing data from an untrusted source.
  339. * <p>
  340. * This is shorthand for:
  341. *
  342. * <pre>
  343. * setObjectChecker(on ? new ObjectChecker() : null);
  344. * </pre>
  345. *
  346. * @param on
  347. * true to enable the default checker; false to disable it.
  348. */
  349. public void setObjectChecking(boolean on) {
  350. setObjectChecker(on ? new ObjectChecker() : null);
  351. }
  352. /**
  353. * Get the message to record with the pack lock.
  354. *
  355. * @return the message to record with the pack lock.
  356. */
  357. public String getLockMessage() {
  358. return lockMessage;
  359. }
  360. /**
  361. * Set the lock message for the incoming pack data.
  362. *
  363. * @param msg
  364. * if not null, the message to associate with the incoming data
  365. * while it is locked to prevent garbage collection.
  366. */
  367. public void setLockMessage(String msg) {
  368. lockMessage = msg;
  369. }
  370. /**
  371. * Set the maximum allowed Git object size.
  372. * <p>
  373. * If an object is larger than the given size the pack-parsing will throw an
  374. * exception aborting the parsing.
  375. *
  376. * @param limit
  377. * the Git object size limit. If zero then there is not limit.
  378. */
  379. public void setMaxObjectSizeLimit(long limit) {
  380. maxObjectSizeLimit = limit;
  381. }
  382. /**
  383. * Get the number of objects in the stream.
  384. * <p>
  385. * The object count is only available after {@link #parse(ProgressMonitor)}
  386. * has returned. The count may have been increased if the stream was a thin
  387. * pack, and missing bases objects were appending onto it by the subclass.
  388. *
  389. * @return number of objects parsed out of the stream.
  390. */
  391. public int getObjectCount() {
  392. return entryCount;
  393. }
  394. /**
  395. * Get the information about the requested object.
  396. * <p>
  397. * The object information is only available after
  398. * {@link #parse(ProgressMonitor)} has returned.
  399. *
  400. * @param nth
  401. * index of the object in the stream. Must be between 0 and
  402. * {@link #getObjectCount()}-1.
  403. * @return the object information.
  404. */
  405. public PackedObjectInfo getObject(int nth) {
  406. return entries[nth];
  407. }
  408. /**
  409. * Get all of the objects, sorted by their name.
  410. * <p>
  411. * The object information is only available after
  412. * {@link #parse(ProgressMonitor)} has returned.
  413. * <p>
  414. * To maintain lower memory usage and good runtime performance, this method
  415. * sorts the objects in-place and therefore impacts the ordering presented
  416. * by {@link #getObject(int)}.
  417. *
  418. * @param cmp
  419. * comparison function, if null objects are stored by ObjectId.
  420. * @return sorted list of objects in this pack stream.
  421. */
  422. public List<PackedObjectInfo> getSortedObjectList(
  423. Comparator<PackedObjectInfo> cmp) {
  424. Arrays.sort(entries, 0, entryCount, cmp);
  425. List<PackedObjectInfo> list = Arrays.asList(entries);
  426. if (entryCount < entries.length)
  427. list = list.subList(0, entryCount);
  428. return list;
  429. }
  430. /**
  431. * Get the size of the newly created pack.
  432. * <p>
  433. * This will also include the pack index size if an index was created. This
  434. * method should only be called after pack parsing is finished.
  435. *
  436. * @return the pack size (including the index size) or -1 if the size cannot
  437. * be determined
  438. * @since 3.3
  439. */
  440. public long getPackSize() {
  441. return -1;
  442. }
  443. /**
  444. * Returns the statistics of the parsed pack.
  445. * <p>
  446. * This should only be called after pack parsing is finished.
  447. *
  448. * @return {@link org.eclipse.jgit.transport.ReceivedPackStatistics}
  449. * @since 4.6
  450. */
  451. public ReceivedPackStatistics getReceivedPackStatistics() {
  452. return stats.build();
  453. }
  454. /**
  455. * Parse the pack stream.
  456. *
  457. * @param progress
  458. * callback to provide progress feedback during parsing. If null,
  459. * {@link org.eclipse.jgit.lib.NullProgressMonitor} will be used.
  460. * @return the pack lock, if one was requested by setting
  461. * {@link #setLockMessage(String)}.
  462. * @throws java.io.IOException
  463. * the stream is malformed, or contains corrupt objects.
  464. * @since 3.0
  465. */
  466. public final PackLock parse(ProgressMonitor progress) throws IOException {
  467. return parse(progress, progress);
  468. }
  469. /**
  470. * Parse the pack stream.
  471. *
  472. * @param receiving
  473. * receives progress feedback during the initial receiving
  474. * objects phase. If null,
  475. * {@link org.eclipse.jgit.lib.NullProgressMonitor} will be used.
  476. * @param resolving
  477. * receives progress feedback during the resolving objects phase.
  478. * @return the pack lock, if one was requested by setting
  479. * {@link #setLockMessage(String)}.
  480. * @throws java.io.IOException
  481. * the stream is malformed, or contains corrupt objects.
  482. * @since 3.0
  483. */
  484. public PackLock parse(ProgressMonitor receiving, ProgressMonitor resolving)
  485. throws IOException {
  486. if (receiving == null)
  487. receiving = NullProgressMonitor.INSTANCE;
  488. if (resolving == null)
  489. resolving = NullProgressMonitor.INSTANCE;
  490. if (receiving == resolving)
  491. receiving.start(2 /* tasks */);
  492. try {
  493. readPackHeader();
  494. entries = new PackedObjectInfo[(int) expectedObjectCount];
  495. baseById = new ObjectIdOwnerMap<>();
  496. baseByPos = new LongMap<>();
  497. collisionCheckObjs = new BlockList<>();
  498. receiving.beginTask(JGitText.get().receivingObjects,
  499. (int) expectedObjectCount);
  500. try {
  501. for (int done = 0; done < expectedObjectCount; done++) {
  502. indexOneObject();
  503. receiving.update(1);
  504. if (receiving.isCancelled())
  505. throw new IOException(JGitText.get().downloadCancelled);
  506. }
  507. readPackFooter();
  508. endInput();
  509. } finally {
  510. receiving.endTask();
  511. }
  512. if (!collisionCheckObjs.isEmpty()) {
  513. checkObjectCollision();
  514. }
  515. if (deltaCount > 0) {
  516. processDeltas(resolving);
  517. }
  518. packDigest = null;
  519. baseById = null;
  520. baseByPos = null;
  521. } finally {
  522. try {
  523. if (readCurs != null)
  524. readCurs.close();
  525. } finally {
  526. readCurs = null;
  527. }
  528. try {
  529. inflater.release();
  530. } finally {
  531. inflater = null;
  532. }
  533. }
  534. return null; // By default there is no locking.
  535. }
  536. private void processDeltas(ProgressMonitor resolving) throws IOException {
  537. if (resolving instanceof BatchingProgressMonitor) {
  538. ((BatchingProgressMonitor) resolving).setDelayStart(1000,
  539. TimeUnit.MILLISECONDS);
  540. }
  541. resolving.beginTask(JGitText.get().resolvingDeltas, deltaCount);
  542. resolveDeltas(resolving);
  543. if (entryCount < expectedObjectCount) {
  544. if (!isAllowThin()) {
  545. throw new IOException(MessageFormat.format(
  546. JGitText.get().packHasUnresolvedDeltas,
  547. Long.valueOf(expectedObjectCount - entryCount)));
  548. }
  549. resolveDeltasWithExternalBases(resolving);
  550. if (entryCount < expectedObjectCount) {
  551. throw new IOException(MessageFormat.format(
  552. JGitText.get().packHasUnresolvedDeltas,
  553. Long.valueOf(expectedObjectCount - entryCount)));
  554. }
  555. }
  556. resolving.endTask();
  557. }
  558. private void resolveDeltas(ProgressMonitor progress)
  559. throws IOException {
  560. final int last = entryCount;
  561. for (int i = 0; i < last; i++) {
  562. resolveDeltas(entries[i], progress);
  563. if (progress.isCancelled())
  564. throw new IOException(
  565. JGitText.get().downloadCancelledDuringIndexing);
  566. }
  567. }
  568. private void resolveDeltas(final PackedObjectInfo oe,
  569. ProgressMonitor progress) throws IOException {
  570. UnresolvedDelta children = firstChildOf(oe);
  571. if (children == null)
  572. return;
  573. DeltaVisit visit = new DeltaVisit();
  574. visit.nextChild = children;
  575. ObjectTypeAndSize info = openDatabase(oe, new ObjectTypeAndSize());
  576. switch (info.type) {
  577. case Constants.OBJ_COMMIT:
  578. case Constants.OBJ_TREE:
  579. case Constants.OBJ_BLOB:
  580. case Constants.OBJ_TAG:
  581. visit.data = inflateAndReturn(Source.DATABASE, info.size);
  582. visit.id = oe;
  583. break;
  584. default:
  585. throw new IOException(MessageFormat.format(
  586. JGitText.get().unknownObjectType,
  587. Integer.valueOf(info.type)));
  588. }
  589. if (!checkCRC(oe.getCRC())) {
  590. throw new IOException(MessageFormat.format(
  591. JGitText.get().corruptionDetectedReReadingAt,
  592. Long.valueOf(oe.getOffset())));
  593. }
  594. resolveDeltas(visit.next(), info.type, info, progress);
  595. }
  596. private void resolveDeltas(DeltaVisit visit, final int type,
  597. ObjectTypeAndSize info, ProgressMonitor progress)
  598. throws IOException {
  599. stats.addDeltaObject(type);
  600. do {
  601. progress.update(1);
  602. info = openDatabase(visit.delta, info);
  603. switch (info.type) {
  604. case Constants.OBJ_OFS_DELTA:
  605. case Constants.OBJ_REF_DELTA:
  606. break;
  607. default:
  608. throw new IOException(MessageFormat.format(
  609. JGitText.get().unknownObjectType,
  610. Integer.valueOf(info.type)));
  611. }
  612. byte[] delta = inflateAndReturn(Source.DATABASE, info.size);
  613. checkIfTooLarge(type, BinaryDelta.getResultSize(delta));
  614. visit.data = BinaryDelta.apply(visit.parent.data, delta);
  615. delta = null;
  616. if (!checkCRC(visit.delta.crc))
  617. throw new IOException(MessageFormat.format(
  618. JGitText.get().corruptionDetectedReReadingAt,
  619. Long.valueOf(visit.delta.position)));
  620. SHA1 objectDigest = objectHasher.reset();
  621. objectDigest.update(Constants.encodedTypeString(type));
  622. objectDigest.update((byte) ' ');
  623. objectDigest.update(Constants.encodeASCII(visit.data.length));
  624. objectDigest.update((byte) 0);
  625. objectDigest.update(visit.data);
  626. objectDigest.digest(tempObjectId);
  627. verifySafeObject(tempObjectId, type, visit.data);
  628. if (isCheckObjectCollisions() && readCurs.has(tempObjectId)) {
  629. checkObjectCollision(tempObjectId, type, visit.data);
  630. }
  631. PackedObjectInfo oe;
  632. oe = newInfo(tempObjectId, visit.delta, visit.parent.id);
  633. oe.setOffset(visit.delta.position);
  634. oe.setType(type);
  635. onInflatedObjectData(oe, type, visit.data);
  636. addObjectAndTrack(oe);
  637. visit.id = oe;
  638. visit.nextChild = firstChildOf(oe);
  639. visit = visit.next();
  640. } while (visit != null);
  641. }
  642. private final void checkIfTooLarge(int typeCode, long size)
  643. throws IOException {
  644. if (0 < maxObjectSizeLimit && maxObjectSizeLimit < size) {
  645. switch (typeCode) {
  646. case Constants.OBJ_COMMIT:
  647. case Constants.OBJ_TREE:
  648. case Constants.OBJ_BLOB:
  649. case Constants.OBJ_TAG:
  650. throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);
  651. case Constants.OBJ_OFS_DELTA:
  652. case Constants.OBJ_REF_DELTA:
  653. throw new TooLargeObjectInPackException(size, maxObjectSizeLimit);
  654. default:
  655. throw new IOException(MessageFormat.format(
  656. JGitText.get().unknownObjectType,
  657. Integer.valueOf(typeCode)));
  658. }
  659. }
  660. if (size > Integer.MAX_VALUE - 8) {
  661. throw new TooLargeObjectInPackException(size, Integer.MAX_VALUE - 8);
  662. }
  663. }
  664. /**
  665. * Read the header of the current object.
  666. * <p>
  667. * After the header has been parsed, this method automatically invokes
  668. * {@link #onObjectHeader(Source, byte[], int, int)} to allow the
  669. * implementation to update its internal checksums for the bytes read.
  670. * <p>
  671. * When this method returns the database will be positioned on the first
  672. * byte of the deflated data stream.
  673. *
  674. * @param info
  675. * the info object to populate.
  676. * @return {@code info}, after populating.
  677. * @throws java.io.IOException
  678. * the size cannot be read.
  679. */
  680. protected ObjectTypeAndSize readObjectHeader(ObjectTypeAndSize info)
  681. throws IOException {
  682. int hdrPtr = 0;
  683. int c = readFrom(Source.DATABASE);
  684. hdrBuf[hdrPtr++] = (byte) c;
  685. info.type = (c >> 4) & 7;
  686. long sz = c & 15;
  687. int shift = 4;
  688. while ((c & 0x80) != 0) {
  689. c = readFrom(Source.DATABASE);
  690. hdrBuf[hdrPtr++] = (byte) c;
  691. sz += ((long) (c & 0x7f)) << shift;
  692. shift += 7;
  693. }
  694. info.size = sz;
  695. switch (info.type) {
  696. case Constants.OBJ_COMMIT:
  697. case Constants.OBJ_TREE:
  698. case Constants.OBJ_BLOB:
  699. case Constants.OBJ_TAG:
  700. onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  701. break;
  702. case Constants.OBJ_OFS_DELTA:
  703. c = readFrom(Source.DATABASE);
  704. hdrBuf[hdrPtr++] = (byte) c;
  705. while ((c & 128) != 0) {
  706. c = readFrom(Source.DATABASE);
  707. hdrBuf[hdrPtr++] = (byte) c;
  708. }
  709. onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  710. break;
  711. case Constants.OBJ_REF_DELTA:
  712. System.arraycopy(buf, fill(Source.DATABASE, 20), hdrBuf, hdrPtr, 20);
  713. hdrPtr += 20;
  714. use(20);
  715. onObjectHeader(Source.DATABASE, hdrBuf, 0, hdrPtr);
  716. break;
  717. default:
  718. throw new IOException(MessageFormat.format(
  719. JGitText.get().unknownObjectType,
  720. Integer.valueOf(info.type)));
  721. }
  722. return info;
  723. }
  724. private UnresolvedDelta removeBaseById(AnyObjectId id) {
  725. final DeltaChain d = baseById.get(id);
  726. return d != null ? d.remove() : null;
  727. }
  728. private static UnresolvedDelta reverse(UnresolvedDelta c) {
  729. UnresolvedDelta tail = null;
  730. while (c != null) {
  731. final UnresolvedDelta n = c.next;
  732. c.next = tail;
  733. tail = c;
  734. c = n;
  735. }
  736. return tail;
  737. }
  738. private UnresolvedDelta firstChildOf(PackedObjectInfo oe) {
  739. UnresolvedDelta a = reverse(removeBaseById(oe));
  740. UnresolvedDelta b = reverse(baseByPos.remove(oe.getOffset()));
  741. if (a == null)
  742. return b;
  743. if (b == null)
  744. return a;
  745. UnresolvedDelta first = null;
  746. UnresolvedDelta last = null;
  747. while (a != null || b != null) {
  748. UnresolvedDelta curr;
  749. if (b == null || (a != null && a.position < b.position)) {
  750. curr = a;
  751. a = a.next;
  752. } else {
  753. curr = b;
  754. b = b.next;
  755. }
  756. if (last != null)
  757. last.next = curr;
  758. else
  759. first = curr;
  760. last = curr;
  761. curr.next = null;
  762. }
  763. return first;
  764. }
  765. private void resolveDeltasWithExternalBases(ProgressMonitor progress)
  766. throws IOException {
  767. growEntries(baseById.size());
  768. if (needBaseObjectIds)
  769. baseObjectIds = new ObjectIdSubclassMap<>();
  770. final List<DeltaChain> missing = new ArrayList<>(64);
  771. for (DeltaChain baseId : baseById) {
  772. if (baseId.head == null)
  773. continue;
  774. if (needBaseObjectIds)
  775. baseObjectIds.add(baseId);
  776. final ObjectLoader ldr;
  777. try {
  778. ldr = readCurs.open(baseId);
  779. } catch (MissingObjectException notFound) {
  780. missing.add(baseId);
  781. continue;
  782. }
  783. final DeltaVisit visit = new DeltaVisit();
  784. visit.data = ldr.getCachedBytes(Integer.MAX_VALUE);
  785. visit.id = baseId;
  786. final int typeCode = ldr.getType();
  787. final PackedObjectInfo oe = newInfo(baseId, null, null);
  788. oe.setType(typeCode);
  789. if (onAppendBase(typeCode, visit.data, oe))
  790. entries[entryCount++] = oe;
  791. visit.nextChild = firstChildOf(oe);
  792. resolveDeltas(visit.next(), typeCode,
  793. new ObjectTypeAndSize(), progress);
  794. if (progress.isCancelled())
  795. throw new IOException(
  796. JGitText.get().downloadCancelledDuringIndexing);
  797. }
  798. for (DeltaChain base : missing) {
  799. if (base.head != null)
  800. throw new MissingObjectException(base, "delta base"); //$NON-NLS-1$
  801. }
  802. onEndThinPack();
  803. }
  804. private void growEntries(int extraObjects) {
  805. final PackedObjectInfo[] ne;
  806. ne = new PackedObjectInfo[(int) expectedObjectCount + extraObjects];
  807. System.arraycopy(entries, 0, ne, 0, entryCount);
  808. entries = ne;
  809. }
  810. private void readPackHeader() throws IOException {
  811. if (expectDataAfterPackFooter) {
  812. if (!in.markSupported())
  813. throw new IOException(
  814. JGitText.get().inputStreamMustSupportMark);
  815. in.mark(buf.length);
  816. }
  817. final int hdrln = Constants.PACK_SIGNATURE.length + 4 + 4;
  818. final int p = fill(Source.INPUT, hdrln);
  819. for (int k = 0; k < Constants.PACK_SIGNATURE.length; k++)
  820. if (buf[p + k] != Constants.PACK_SIGNATURE[k])
  821. throw new IOException(JGitText.get().notAPACKFile);
  822. final long vers = NB.decodeUInt32(buf, p + 4);
  823. if (vers != 2 && vers != 3)
  824. throw new IOException(MessageFormat.format(
  825. JGitText.get().unsupportedPackVersion, Long.valueOf(vers)));
  826. final long objectCount = NB.decodeUInt32(buf, p + 8);
  827. use(hdrln);
  828. setExpectedObjectCount(objectCount);
  829. onPackHeader(objectCount);
  830. }
  831. private void readPackFooter() throws IOException {
  832. sync();
  833. final byte[] actHash = packDigest.digest();
  834. final int c = fill(Source.INPUT, 20);
  835. final byte[] srcHash = new byte[20];
  836. System.arraycopy(buf, c, srcHash, 0, 20);
  837. use(20);
  838. if (bAvail != 0 && !expectDataAfterPackFooter)
  839. throw new CorruptObjectException(MessageFormat.format(
  840. JGitText.get().expectedEOFReceived,
  841. "\\x" + Integer.toHexString(buf[bOffset] & 0xff))); //$NON-NLS-1$
  842. if (isCheckEofAfterPackFooter()) {
  843. int eof = in.read();
  844. if (0 <= eof)
  845. throw new CorruptObjectException(MessageFormat.format(
  846. JGitText.get().expectedEOFReceived,
  847. "\\x" + Integer.toHexString(eof))); //$NON-NLS-1$
  848. } else if (bAvail > 0 && expectDataAfterPackFooter) {
  849. in.reset();
  850. IO.skipFully(in, bOffset);
  851. }
  852. if (!Arrays.equals(actHash, srcHash))
  853. throw new CorruptObjectException(
  854. JGitText.get().corruptObjectPackfileChecksumIncorrect);
  855. onPackFooter(srcHash);
  856. }
  857. // Cleanup all resources associated with our input parsing.
  858. private void endInput() {
  859. stats.setNumBytesRead(streamPosition());
  860. in = null;
  861. }
  862. // Read one entire object or delta from the input.
  863. private void indexOneObject() throws IOException {
  864. final long streamPosition = streamPosition();
  865. int hdrPtr = 0;
  866. int c = readFrom(Source.INPUT);
  867. hdrBuf[hdrPtr++] = (byte) c;
  868. final int typeCode = (c >> 4) & 7;
  869. long sz = c & 15;
  870. int shift = 4;
  871. while ((c & 0x80) != 0) {
  872. c = readFrom(Source.INPUT);
  873. hdrBuf[hdrPtr++] = (byte) c;
  874. sz += ((long) (c & 0x7f)) << shift;
  875. shift += 7;
  876. }
  877. checkIfTooLarge(typeCode, sz);
  878. switch (typeCode) {
  879. case Constants.OBJ_COMMIT:
  880. case Constants.OBJ_TREE:
  881. case Constants.OBJ_BLOB:
  882. case Constants.OBJ_TAG:
  883. stats.addWholeObject(typeCode);
  884. onBeginWholeObject(streamPosition, typeCode, sz);
  885. onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  886. whole(streamPosition, typeCode, sz);
  887. break;
  888. case Constants.OBJ_OFS_DELTA: {
  889. stats.addOffsetDelta();
  890. c = readFrom(Source.INPUT);
  891. hdrBuf[hdrPtr++] = (byte) c;
  892. long ofs = c & 127;
  893. while ((c & 128) != 0) {
  894. ofs += 1;
  895. c = readFrom(Source.INPUT);
  896. hdrBuf[hdrPtr++] = (byte) c;
  897. ofs <<= 7;
  898. ofs += (c & 127);
  899. }
  900. final long base = streamPosition - ofs;
  901. onBeginOfsDelta(streamPosition, base, sz);
  902. onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  903. inflateAndSkip(Source.INPUT, sz);
  904. UnresolvedDelta n = onEndDelta();
  905. n.position = streamPosition;
  906. n.next = baseByPos.put(base, n);
  907. deltaCount++;
  908. break;
  909. }
  910. case Constants.OBJ_REF_DELTA: {
  911. stats.addRefDelta();
  912. c = fill(Source.INPUT, 20);
  913. final ObjectId base = ObjectId.fromRaw(buf, c);
  914. System.arraycopy(buf, c, hdrBuf, hdrPtr, 20);
  915. hdrPtr += 20;
  916. use(20);
  917. DeltaChain r = baseById.get(base);
  918. if (r == null) {
  919. r = new DeltaChain(base);
  920. baseById.add(r);
  921. }
  922. onBeginRefDelta(streamPosition, base, sz);
  923. onObjectHeader(Source.INPUT, hdrBuf, 0, hdrPtr);
  924. inflateAndSkip(Source.INPUT, sz);
  925. UnresolvedDelta n = onEndDelta();
  926. n.position = streamPosition;
  927. r.add(n);
  928. deltaCount++;
  929. break;
  930. }
  931. default:
  932. throw new IOException(
  933. MessageFormat.format(JGitText.get().unknownObjectType,
  934. Integer.valueOf(typeCode)));
  935. }
  936. }
  937. private void whole(long pos, int type, long sz)
  938. throws IOException {
  939. SHA1 objectDigest = objectHasher.reset();
  940. objectDigest.update(Constants.encodedTypeString(type));
  941. objectDigest.update((byte) ' ');
  942. objectDigest.update(Constants.encodeASCII(sz));
  943. objectDigest.update((byte) 0);
  944. final byte[] data;
  945. if (type == Constants.OBJ_BLOB) {
  946. byte[] readBuffer = buffer();
  947. BlobObjectChecker checker = null;
  948. if (objCheck != null) {
  949. checker = objCheck.newBlobObjectChecker();
  950. }
  951. if (checker == null) {
  952. checker = BlobObjectChecker.NULL_CHECKER;
  953. }
  954. long cnt = 0;
  955. try (InputStream inf = inflate(Source.INPUT, sz)) {
  956. while (cnt < sz) {
  957. int r = inf.read(readBuffer);
  958. if (r <= 0)
  959. break;
  960. objectDigest.update(readBuffer, 0, r);
  961. checker.update(readBuffer, 0, r);
  962. cnt += r;
  963. }
  964. }
  965. objectDigest.digest(tempObjectId);
  966. checker.endBlob(tempObjectId);
  967. data = null;
  968. } else {
  969. data = inflateAndReturn(Source.INPUT, sz);
  970. objectDigest.update(data);
  971. objectDigest.digest(tempObjectId);
  972. verifySafeObject(tempObjectId, type, data);
  973. }
  974. PackedObjectInfo obj = newInfo(tempObjectId, null, null);
  975. obj.setOffset(pos);
  976. obj.setType(type);
  977. onEndWholeObject(obj);
  978. if (data != null)
  979. onInflatedObjectData(obj, type, data);
  980. addObjectAndTrack(obj);
  981. if (isCheckObjectCollisions()) {
  982. collisionCheckObjs.add(obj);
  983. }
  984. }
  985. /**
  986. * Verify the integrity of the object.
  987. *
  988. * @param id
  989. * identity of the object to be checked.
  990. * @param type
  991. * the type of the object.
  992. * @param data
  993. * raw content of the object.
  994. * @throws org.eclipse.jgit.errors.CorruptObjectException
  995. * @since 4.9
  996. */
  997. protected void verifySafeObject(final AnyObjectId id, final int type,
  998. final byte[] data) throws CorruptObjectException {
  999. if (objCheck != null) {
  1000. try {
  1001. objCheck.check(id, type, data);
  1002. } catch (CorruptObjectException e) {
  1003. if (e.getErrorType() != null) {
  1004. throw e;
  1005. }
  1006. throw new CorruptObjectException(
  1007. MessageFormat.format(JGitText.get().invalidObject,
  1008. Constants.typeString(type), id.name(),
  1009. e.getMessage()),
  1010. e);
  1011. }
  1012. }
  1013. }
  1014. private void checkObjectCollision() throws IOException {
  1015. for (PackedObjectInfo obj : collisionCheckObjs) {
  1016. if (!readCurs.has(obj)) {
  1017. continue;
  1018. }
  1019. checkObjectCollision(obj);
  1020. }
  1021. }
  1022. private void checkObjectCollision(PackedObjectInfo obj)
  1023. throws IOException {
  1024. ObjectTypeAndSize info = openDatabase(obj, new ObjectTypeAndSize());
  1025. final byte[] readBuffer = buffer();
  1026. final byte[] curBuffer = new byte[readBuffer.length];
  1027. long sz = info.size;
  1028. try (ObjectStream cur = readCurs.open(obj, info.type).openStream()) {
  1029. if (cur.getSize() != sz) {
  1030. throw new IOException(MessageFormat.format(
  1031. JGitText.get().collisionOn, obj.name()));
  1032. }
  1033. try (InputStream pck = inflate(Source.DATABASE, sz)) {
  1034. while (0 < sz) {
  1035. int n = (int) Math.min(readBuffer.length, sz);
  1036. IO.readFully(cur, curBuffer, 0, n);
  1037. IO.readFully(pck, readBuffer, 0, n);
  1038. for (int i = 0; i < n; i++) {
  1039. if (curBuffer[i] != readBuffer[i]) {
  1040. throw new IOException(MessageFormat.format(
  1041. JGitText.get().collisionOn, obj.name()));
  1042. }
  1043. }
  1044. sz -= n;
  1045. }
  1046. }
  1047. } catch (MissingObjectException notLocal) {
  1048. // This is OK, we don't have a copy of the object locally
  1049. // but the API throws when we try to read it as usually it's
  1050. // an error to read something that doesn't exist.
  1051. }
  1052. }
  1053. private void checkObjectCollision(AnyObjectId obj, int type, byte[] data)
  1054. throws IOException {
  1055. try {
  1056. final ObjectLoader ldr = readCurs.open(obj, type);
  1057. final byte[] existingData = ldr.getCachedBytes(data.length);
  1058. if (!Arrays.equals(data, existingData)) {
  1059. throw new IOException(MessageFormat.format(
  1060. JGitText.get().collisionOn, obj.name()));
  1061. }
  1062. } catch (MissingObjectException notLocal) {
  1063. // This is OK, we don't have a copy of the object locally
  1064. // but the API throws when we try to read it as usually its
  1065. // an error to read something that doesn't exist.
  1066. }
  1067. }
  1068. /** @return current position of the input stream being parsed. */
  1069. private long streamPosition() {
  1070. return bBase + bOffset;
  1071. }
  1072. private ObjectTypeAndSize openDatabase(PackedObjectInfo obj,
  1073. ObjectTypeAndSize info) throws IOException {
  1074. bOffset = 0;
  1075. bAvail = 0;
  1076. return seekDatabase(obj, info);
  1077. }
  1078. private ObjectTypeAndSize openDatabase(UnresolvedDelta delta,
  1079. ObjectTypeAndSize info) throws IOException {
  1080. bOffset = 0;
  1081. bAvail = 0;
  1082. return seekDatabase(delta, info);
  1083. }
  1084. // Consume exactly one byte from the buffer and return it.
  1085. private int readFrom(Source src) throws IOException {
  1086. if (bAvail == 0)
  1087. fill(src, 1);
  1088. bAvail--;
  1089. return buf[bOffset++] & 0xff;
  1090. }
  1091. // Consume cnt bytes from the buffer.
  1092. void use(int cnt) {
  1093. bOffset += cnt;
  1094. bAvail -= cnt;
  1095. }
  1096. // Ensure at least need bytes are available in {@link #buf}.
  1097. int fill(Source src, int need) throws IOException {
  1098. while (bAvail < need) {
  1099. int next = bOffset + bAvail;
  1100. int free = buf.length - next;
  1101. if (free + bAvail < need) {
  1102. switch (src) {
  1103. case INPUT:
  1104. sync();
  1105. break;
  1106. case DATABASE:
  1107. if (bAvail > 0)
  1108. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  1109. bOffset = 0;
  1110. break;
  1111. }
  1112. next = bAvail;
  1113. free = buf.length - next;
  1114. }
  1115. switch (src) {
  1116. case INPUT:
  1117. next = in.read(buf, next, free);
  1118. break;
  1119. case DATABASE:
  1120. next = readDatabase(buf, next, free);
  1121. break;
  1122. }
  1123. if (next <= 0)
  1124. throw new EOFException(
  1125. JGitText.get().packfileIsTruncatedNoParam);
  1126. bAvail += next;
  1127. }
  1128. return bOffset;
  1129. }
  1130. // Store consumed bytes in {@link #buf} up to {@link #bOffset}.
  1131. private void sync() throws IOException {
  1132. packDigest.update(buf, 0, bOffset);
  1133. onStoreStream(buf, 0, bOffset);
  1134. if (expectDataAfterPackFooter) {
  1135. if (bAvail > 0) {
  1136. in.reset();
  1137. IO.skipFully(in, bOffset);
  1138. bAvail = 0;
  1139. }
  1140. in.mark(buf.length);
  1141. } else if (bAvail > 0)
  1142. System.arraycopy(buf, bOffset, buf, 0, bAvail);
  1143. bBase += bOffset;
  1144. bOffset = 0;
  1145. }
  1146. /**
  1147. * Get a temporary byte array for use by the caller.
  1148. *
  1149. * @return a temporary byte array for use by the caller.
  1150. */
  1151. protected byte[] buffer() {
  1152. return tempBuffer;
  1153. }
  1154. /**
  1155. * Construct a PackedObjectInfo instance for this parser.
  1156. *
  1157. * @param id
  1158. * identity of the object to be tracked.
  1159. * @param delta
  1160. * if the object was previously an unresolved delta, this is the
  1161. * delta object that was tracking it. Otherwise null.
  1162. * @param deltaBase
  1163. * if the object was previously an unresolved delta, this is the
  1164. * ObjectId of the base of the delta. The base may be outside of
  1165. * the pack stream if the stream was a thin-pack.
  1166. * @return info object containing this object's data.
  1167. */
  1168. protected PackedObjectInfo newInfo(AnyObjectId id, UnresolvedDelta delta,
  1169. ObjectId deltaBase) {
  1170. PackedObjectInfo oe = new PackedObjectInfo(id);
  1171. if (delta != null)
  1172. oe.setCRC(delta.crc);
  1173. return oe;
  1174. }
  1175. /**
  1176. * Set the expected number of objects in the pack stream.
  1177. * <p>
  1178. * The object count in the pack header is not always correct for some Dfs
  1179. * pack files. e.g. INSERT pack always assume 1 object in the header since
  1180. * the actual object count is unknown when the pack is written.
  1181. * <p>
  1182. * If external implementation wants to overwrite the expectedObjectCount,
  1183. * they should call this method during {@link #onPackHeader(long)}.
  1184. *
  1185. * @param expectedObjectCount a long.
  1186. * @since 4.9
  1187. */
  1188. protected void setExpectedObjectCount(long expectedObjectCount) {
  1189. this.expectedObjectCount = expectedObjectCount;
  1190. }
  1191. /**
  1192. * Store bytes received from the raw stream.
  1193. * <p>
  1194. * This method is invoked during {@link #parse(ProgressMonitor)} as data is
  1195. * consumed from the incoming stream. Implementors may use this event to
  1196. * archive the raw incoming stream to the destination repository in large
  1197. * chunks, without paying attention to object boundaries.
  1198. * <p>
  1199. * The only component of the pack not supplied to this method is the last 20
  1200. * bytes of the pack that comprise the trailing SHA-1 checksum. Those are
  1201. * passed to {@link #onPackFooter(byte[])}.
  1202. *
  1203. * @param raw
  1204. * buffer to copy data out of.
  1205. * @param pos
  1206. * first offset within the buffer that is valid.
  1207. * @param len
  1208. * number of bytes in the buffer that are valid.
  1209. * @throws java.io.IOException
  1210. * the stream cannot be archived.
  1211. */
  1212. protected abstract void onStoreStream(byte[] raw, int pos, int len)
  1213. throws IOException;
  1214. /**
  1215. * Store (and/or checksum) an object header.
  1216. * <p>
  1217. * Invoked after any of the {@code onBegin()} events. The entire header is
  1218. * supplied in a single invocation, before any object data is supplied.
  1219. *
  1220. * @param src
  1221. * where the data came from
  1222. * @param raw
  1223. * buffer to read data from.
  1224. * @param pos
  1225. * first offset within buffer that is valid.
  1226. * @param len
  1227. * number of bytes in buffer that are valid.
  1228. * @throws java.io.IOException
  1229. * the stream cannot be archived.
  1230. */
  1231. protected abstract void onObjectHeader(Source src, byte[] raw, int pos,
  1232. int len) throws IOException;
  1233. /**
  1234. * Store (and/or checksum) a portion of an object's data.
  1235. * <p>
  1236. * This method may be invoked multiple times per object, depending on the
  1237. * size of the object, the size of the parser's internal read buffer, and
  1238. * the alignment of the object relative to the read buffer.
  1239. * <p>
  1240. * Invoked after {@link #onObjectHeader(Source, byte[], int, int)}.
  1241. *
  1242. * @param src
  1243. * where the data came from
  1244. * @param raw
  1245. * buffer to read data from.
  1246. * @param pos
  1247. * first offset within buffer that is valid.
  1248. * @param len
  1249. * number of bytes in buffer that are valid.
  1250. * @throws java.io.IOException
  1251. * the stream cannot be archived.
  1252. */
  1253. protected abstract void onObjectData(Source src, byte[] raw, int pos,
  1254. int len) throws IOException;
  1255. /**
  1256. * Invoked for commits, trees, tags, and small blobs.
  1257. *
  1258. * @param obj
  1259. * the object info, populated.
  1260. * @param typeCode
  1261. * the type of the object.
  1262. * @param data
  1263. * inflated data for the object.
  1264. * @throws java.io.IOException
  1265. * the object cannot be archived.
  1266. */
  1267. protected abstract void onInflatedObjectData(PackedObjectInfo obj,
  1268. int typeCode, byte[] data) throws IOException;
  1269. /**
  1270. * Provide the implementation with the original stream's pack header.
  1271. *
  1272. * @param objCnt
  1273. * number of objects expected in the stream.
  1274. * @throws java.io.IOException
  1275. * the implementation refuses to work with this many objects.
  1276. */
  1277. protected abstract void onPackHeader(long objCnt) throws IOException;
  1278. /**
  1279. * Provide the implementation with the original stream's pack footer.
  1280. *
  1281. * @param hash
  1282. * the trailing 20 bytes of the pack, this is a SHA-1 checksum of
  1283. * all of the pack data.
  1284. * @throws java.io.IOException
  1285. * the stream cannot be archived.
  1286. */
  1287. protected abstract void onPackFooter(byte[] hash) throws IOException;
  1288. /**
  1289. * Provide the implementation with a base that was outside of the pack.
  1290. * <p>
  1291. * This event only occurs on a thin pack for base objects that were outside
  1292. * of the pack and came from the local repository. Usually an implementation
  1293. * uses this event to compress the base and append it onto the end of the
  1294. * pack, so the pack stays self-contained.
  1295. *
  1296. * @param typeCode
  1297. * type of the base object.
  1298. * @param data
  1299. * complete content of the base object.
  1300. * @param info
  1301. * packed object information for this base. Implementors must
  1302. * populate the CRC and offset members if returning true.
  1303. * @return true if the {@code info} should be included in the object list
  1304. * returned by {@link #getSortedObjectList(Comparator)}, false if it
  1305. * should not be included.
  1306. * @throws java.io.IOException
  1307. * the base could not be included into the pack.
  1308. */
  1309. protected abstract boolean onAppendBase(int typeCode, byte[] data,
  1310. PackedObjectInfo info) throws IOException;
  1311. /**
  1312. * Event indicating a thin pack has been completely processed.
  1313. * <p>
  1314. * This event is invoked only if a thin pack has delta references to objects
  1315. * external from the pack. The event is called after all of those deltas
  1316. * have been resolved.
  1317. *
  1318. * @throws java.io.IOException
  1319. * the pack cannot be archived.
  1320. */
  1321. protected abstract void onEndThinPack() throws IOException;
  1322. /**
  1323. * Reposition the database to re-read a previously stored object.
  1324. * <p>
  1325. * If the database is computing CRC-32 checksums for object data, it should
  1326. * reset its internal CRC instance during this method call.
  1327. *
  1328. * @param obj
  1329. * the object position to begin reading from. This is from
  1330. * {@link #newInfo(AnyObjectId, UnresolvedDelta, ObjectId)}.
  1331. * @param info
  1332. * object to populate with type and size.
  1333. * @return the {@code info} object.
  1334. * @throws java.io.IOException
  1335. * the database cannot reposition to this location.
  1336. */
  1337. protected abstract ObjectTypeAndSize seekDatabase(PackedObjectInfo obj,
  1338. ObjectTypeAndSize info) throws IOException;
  1339. /**
  1340. * Reposition the database to re-read a previously stored object.
  1341. * <p>
  1342. * If the database is computing CRC-32 checksums for object data, it should
  1343. * reset its internal CRC instance during this method call.
  1344. *
  1345. * @param delta
  1346. * the object position to begin reading from. This is an instance
  1347. * previously returned by {@link #onEndDelta()}.
  1348. * @param info
  1349. * object to populate with type and size.
  1350. * @return the {@code info} object.
  1351. * @throws java.io.IOException
  1352. * the database cannot reposition to this location.
  1353. */
  1354. protected abstract ObjectTypeAndSize seekDatabase(UnresolvedDelta delta,
  1355. ObjectTypeAndSize info) throws IOException;
  1356. /**
  1357. * Read from the database's current position into the buffer.
  1358. *
  1359. * @param dst
  1360. * the buffer to copy read data into.
  1361. * @param pos
  1362. * position within {@code dst} to start copying data into.
  1363. * @param cnt
  1364. * ideal target number of bytes to read. Actual read length may
  1365. * be shorter.
  1366. * @return number of bytes stored.
  1367. * @throws java.io.IOException
  1368. * the database cannot be accessed.
  1369. */
  1370. protected abstract int readDatabase(byte[] dst, int pos, int cnt)
  1371. throws IOException;
  1372. /**
  1373. * Check the current CRC matches the expected value.
  1374. * <p>
  1375. * This method is invoked when an object is read back in from the database
  1376. * and its data is used during delta resolution. The CRC is validated after
  1377. * the object has been fully read, allowing the parser to verify there was
  1378. * no silent data corruption.
  1379. * <p>
  1380. * Implementations are free to ignore this check by always returning true if
  1381. * they are performing other data integrity validations at a lower level.
  1382. *
  1383. * @param oldCRC
  1384. * the prior CRC that was recorded during the first scan of the
  1385. * object from the pack stream.
  1386. * @return true if the CRC matches; false if it does not.
  1387. */
  1388. protected abstract boolean checkCRC(int oldCRC);
  1389. /**
  1390. * Event notifying the start of an object stored whole (not as a delta).
  1391. *
  1392. * @param streamPosition
  1393. * position of this object in the incoming stream.
  1394. * @param type
  1395. * type of the object; one of
  1396. * {@link org.eclipse.jgit.lib.Constants#OBJ_COMMIT},
  1397. * {@link org.eclipse.jgit.lib.Constants#OBJ_TREE},
  1398. * {@link org.eclipse.jgit.lib.Constants#OBJ_BLOB}, or
  1399. * {@link org.eclipse.jgit.lib.Constants#OBJ_TAG}.
  1400. * @param inflatedSize
  1401. * size of the object when fully inflated. The size stored within
  1402. * the pack may be larger or smaller, and is not yet known.
  1403. * @throws java.io.IOException
  1404. * the object cannot be recorded.
  1405. */
  1406. protected abstract void onBeginWholeObject(long streamPosition, int type,
  1407. long inflatedSize) throws IOException;
  1408. /**
  1409. * Event notifying the current object.
  1410. *
  1411. *@param info
  1412. * object information.
  1413. * @throws java.io.IOException
  1414. * the object cannot be recorded.
  1415. */
  1416. protected abstract void onEndWholeObject(PackedObjectInfo info)
  1417. throws IOException;
  1418. /**
  1419. * Event notifying start of a delta referencing its base by offset.
  1420. *
  1421. * @param deltaStreamPosition
  1422. * position of this object in the incoming stream.
  1423. * @param baseStreamPosition
  1424. * position of the base object in the incoming stream. The base
  1425. * must be before the delta, therefore {@code baseStreamPosition
  1426. * &lt; deltaStreamPosition}. This is <b>not</b> the position
  1427. * returned by a prior end object event.
  1428. * @param inflatedSize
  1429. * size of the delta when fully inflated. The size stored within
  1430. * the pack may be larger or smaller, and is not yet known.
  1431. * @throws java.io.IOException
  1432. * the object cannot be recorded.
  1433. */
  1434. protected abstract void onBeginOfsDelta(long deltaStreamPosition,
  1435. long baseStreamPosition, long inflatedSize) throws IOException;
  1436. /**
  1437. * Event notifying start of a delta referencing its base by ObjectId.
  1438. *
  1439. * @param deltaStreamPosition
  1440. * position of this object in the incoming stream.
  1441. * @param baseId
  1442. * name of the base object. This object may be later in the
  1443. * stream, or might not appear at all in the stream (in the case
  1444. * of a thin-pack).
  1445. * @param inflatedSize
  1446. * size of the delta when fully inflated. The size stored within
  1447. * the pack may be larger or smaller, and is not yet known.
  1448. * @throws java.io.IOException
  1449. * the object cannot be recorded.
  1450. */
  1451. protected abstract void onBeginRefDelta(long deltaStreamPosition,
  1452. AnyObjectId baseId, long inflatedSize) throws IOException;
  1453. /**
  1454. * Event notifying the current object.
  1455. *
  1456. *@return object information that must be populated with at least the
  1457. * offset.
  1458. * @throws java.io.IOException
  1459. * the object cannot be recorded.
  1460. */
  1461. protected UnresolvedDelta onEndDelta() throws IOException {
  1462. return new UnresolvedDelta();
  1463. }
  1464. /** Type and size information about an object in the database buffer. */
  1465. public static class ObjectTypeAndSize {
  1466. /** The type of the object. */
  1467. public int type;
  1468. /** The inflated size of the object. */
  1469. public long size;
  1470. }
  1471. private void inflateAndSkip(Source src, long inflatedSize)
  1472. throws IOException {
  1473. try (InputStream inf = inflate(src, inflatedSize)) {
  1474. IO.skipFully(inf, inflatedSize);
  1475. }
  1476. }
  1477. private byte[] inflateAndReturn(Source src, long inflatedSize)
  1478. throws IOException {
  1479. final byte[] dst = new byte[(int) inflatedSize];
  1480. try (InputStream inf = inflate(src, inflatedSize)) {
  1481. IO.readFully(inf, dst, 0, dst.length);
  1482. }
  1483. return dst;
  1484. }
  1485. private InputStream inflate(Source src, long inflatedSize)
  1486. throws IOException {
  1487. inflater.open(src, inflatedSize);
  1488. return inflater;
  1489. }
  1490. private static class DeltaChain extends ObjectIdOwnerMap.Entry {
  1491. UnresolvedDelta head;
  1492. DeltaChain(AnyObjectId id) {
  1493. super(id);
  1494. }
  1495. UnresolvedDelta remove() {
  1496. final UnresolvedDelta r = head;
  1497. if (r != null)
  1498. head = null;
  1499. return r;
  1500. }
  1501. void add(UnresolvedDelta d) {
  1502. d.next = head;
  1503. head = d;
  1504. }
  1505. }
  1506. /** Information about an unresolved delta in this pack stream. */
  1507. public static class UnresolvedDelta {
  1508. long position;
  1509. int crc;
  1510. UnresolvedDelta next;
  1511. /** @return offset within the input stream. */
  1512. public long getOffset() {
  1513. return position;
  1514. }
  1515. /** @return the CRC-32 checksum of the stored delta data. */
  1516. public int getCRC() {
  1517. return crc;
  1518. }
  1519. /**
  1520. * @param crc32
  1521. * the CRC-32 checksum of the stored delta data.
  1522. */
  1523. public void setCRC(int crc32) {
  1524. crc = crc32;
  1525. }
  1526. }
  1527. private static class DeltaVisit {
  1528. final UnresolvedDelta delta;
  1529. ObjectId id;
  1530. byte[] data;
  1531. DeltaVisit parent;
  1532. UnresolvedDelta nextChild;
  1533. DeltaVisit() {
  1534. this.delta = null; // At the root of the stack we have a base.
  1535. }
  1536. DeltaVisit(DeltaVisit parent) {
  1537. this.parent = parent;
  1538. this.delta = parent.nextChild;
  1539. parent.nextChild = delta.next;
  1540. }
  1541. DeltaVisit next() {
  1542. // If our parent has no more children, discard it.
  1543. if (parent != null && parent.nextChild == null) {
  1544. parent.data = null;
  1545. parent = parent.parent;
  1546. }
  1547. if (nextChild != null)
  1548. return new DeltaVisit(this);
  1549. // If we have no child ourselves, our parent must (if it exists),
  1550. // due to the discard rule above. With no parent, we are done.
  1551. if (parent != null)
  1552. return new DeltaVisit(parent);
  1553. return null;
  1554. }
  1555. }
  1556. private void addObjectAndTrack(PackedObjectInfo oe) {
  1557. entries[entryCount++] = oe;
  1558. if (needNewObjectIds())
  1559. newObjectIds.add(oe);
  1560. }
  1561. private class InflaterStream extends InputStream {
  1562. private final Inflater inf;
  1563. private final byte[] skipBuffer;
  1564. private Source src;
  1565. private long expectedSize;
  1566. private long actualSize;
  1567. private int p;
  1568. InflaterStream() {
  1569. inf = InflaterCache.get();
  1570. skipBuffer = new byte[512];
  1571. }
  1572. void release() {
  1573. inf.reset();
  1574. InflaterCache.release(inf);
  1575. }
  1576. void open(Source source, long inflatedSize) throws IOException {
  1577. src = source;
  1578. expectedSize = inflatedSize;
  1579. actualSize = 0;
  1580. p = fill(src, 1);
  1581. inf.setInput(buf, p, bAvail);
  1582. }
  1583. @Override
  1584. public long skip(long toSkip) throws IOException {
  1585. long n = 0;
  1586. while (n < toSkip) {
  1587. final int cnt = (int) Math.min(skipBuffer.length, toSkip - n);
  1588. final int r = read(skipBuffer, 0, cnt);
  1589. if (r <= 0)
  1590. break;
  1591. n += r;
  1592. }
  1593. return n;
  1594. }
  1595. @Override
  1596. public int read() throws IOException {
  1597. int n = read(skipBuffer, 0, 1);
  1598. return n == 1 ? skipBuffer[0] & 0xff : -1;
  1599. }
  1600. @Override
  1601. public int read(byte[] dst, int pos, int cnt) throws IOException {
  1602. try {
  1603. int n = 0;
  1604. while (n < cnt) {
  1605. int r = inf.inflate(dst, pos + n, cnt - n);
  1606. n += r;
  1607. if (inf.finished())
  1608. break;
  1609. if (inf.needsInput()) {
  1610. onObjectData(src, buf, p, bAvail);
  1611. use(bAvail);
  1612. p = fill(src, 1);
  1613. inf.setInput(buf, p, bAvail);
  1614. } else if (r == 0) {
  1615. throw new CorruptObjectException(MessageFormat.format(
  1616. JGitText.get().packfileCorruptionDetected,
  1617. JGitText.get().unknownZlibError));
  1618. }
  1619. }
  1620. actualSize += n;
  1621. return 0 < n ? n : -1;
  1622. } catch (DataFormatException dfe) {
  1623. throw new CorruptObjectException(MessageFormat.format(JGitText
  1624. .get().packfileCorruptionDetected, dfe.getMessage()));
  1625. }
  1626. }
  1627. @Override
  1628. public void close() throws IOException {
  1629. // We need to read here to enter the loop above and pump the
  1630. // trailing checksum into the Inflater. It should return -1 as the
  1631. // caller was supposed to consume all content.
  1632. //
  1633. if (read(skipBuffer) != -1 || actualSize != expectedSize) {
  1634. throw new CorruptObjectException(MessageFormat.format(JGitText
  1635. .get().packfileCorruptionDetected,
  1636. JGitText.get().wrongDecompressedLength));
  1637. }
  1638. int used = bAvail - inf.getRemaining();
  1639. if (0 < used) {
  1640. onObjectData(src, buf, p, used);
  1641. use(used);
  1642. }
  1643. inf.reset();
  1644. }
  1645. }
  1646. }