code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
func(ctx etreeutils.NSContext, signedInfo *etree.Element) error {
detachedSignedInfo, err := etreeutils.NSDetatch(ctx, signedInfo)
if err != nil {
return err
}
c14NMethod, err := etreeutils.NSFindOneChildCtx(ctx, detachedSignedInfo, Namespace, CanonicalizationMethodTag)
if err != nil {
return err
}
if c14NMethod == nil {
return errors.New("missing CanonicalizationMethod on Signature")
}
c14NAlgorithm := c14NMethod.SelectAttrValue(AlgorithmAttr, "")
var canonicalSignedInfo *etree.Element
switch AlgorithmID(c14NAlgorithm) {
case CanonicalXML10ExclusiveAlgorithmId:
err := etreeutils.TransformExcC14n(detachedSignedInfo, "")
if err != nil {
return err
}
// NOTE: TransformExcC14n transforms the element in-place,
// while canonicalPrep isn't meant to. Once we standardize
// this behavior we can drop this, as well as the adding and
// removing of elements below.
canonicalSignedInfo = detachedSignedInfo
case CanonicalXML11AlgorithmId:
canonicalSignedInfo = canonicalPrep(detachedSignedInfo, map[string]struct{}{})
case CanonicalXML10RecAlgorithmId:
canonicalSignedInfo = canonicalPrep(detachedSignedInfo, map[string]struct{}{})
case CanonicalXML10CommentAlgorithmId:
canonicalSignedInfo = canonicalPrep(detachedSignedInfo, map[string]struct{}{})
default:
return fmt.Errorf("invalid CanonicalizationMethod on Signature: %s", c14NAlgorithm)
}
el.RemoveChild(signedInfo)
el.AddChild(canonicalSignedInfo)
found = true
return etreeutils.ErrTraversalHalted
}) | Base | 1 |
func InstallNps() {
path := common.GetInstallPath()
if common.FileExists(path) {
log.Fatalf("the path %s has exist, does not support install", path)
}
MkidrDirAll(path, "conf", "web/static", "web/views")
//复制文件到对应目录
if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "views"), filepath.Join(path, "web", "views")); err != nil {
log.Fatalln(err)
}
if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "static"), filepath.Join(path, "web", "static")); err != nil {
log.Fatalln(err)
}
if err := CopyDir(filepath.Join(common.GetAppPath(), "conf"), filepath.Join(path, "conf")); err != nil {
log.Fatalln(err)
}
if !common.IsWindows() {
if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/bin/nps"); err != nil {
if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/local/bin/nps"); err != nil {
log.Fatalln(err)
} else {
os.Chmod("/usr/local/bin/nps", 0777)
log.Println("Executable files have been copied to", "/usr/local/bin/nps")
}
} else {
os.Chmod("/usr/bin/nps", 0777)
log.Println("Executable files have been copied to", "/usr/bin/nps")
}
}
log.Println("install ok!")
log.Println("Static files and configuration files in the current directory will be useless")
log.Println("The new configuration file is located in", path, "you can edit them")
if !common.IsWindows() {
log.Println("You can start with nps test|start|stop|restart|status anywhere")
} else {
log.Println("You can copy executable files to any directory and start working with nps.exe test|start|stop|restart|status")
}
} | Class | 2 |
func (*Config_Warning) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{14, 0}
} | Base | 1 |
func padBuffer(buffer []byte, blockSize int) []byte {
missing := blockSize - (len(buffer) % blockSize)
ret, out := resize(buffer, len(buffer)+missing)
padding := bytes.Repeat([]byte{byte(missing)}, missing)
copy(out, padding)
return ret
} | Base | 1 |
func (m *FloatingPoint) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTheproto3
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: FloatingPoint: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: FloatingPoint: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field F", wireType)
}
var v uint64
if (iNdEx + 8) > l {
return io.ErrUnexpectedEOF
}
v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:]))
iNdEx += 8
m.F = float64(math.Float64frombits(v))
default:
iNdEx = preIndex
skippy, err := skipTheproto3(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthTheproto3
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthTheproto3
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (p *CompactProtocol) ReadFieldBegin() (name string, typeId Type, id int16, err error) {
t, err := p.readByteDirect()
if err != nil {
return
}
// if it's a stop, then we can return immediately, as the struct is over.
if (t & 0x0f) == STOP {
return "", STOP, 0, nil
}
// mask off the 4 MSB of the type header. it could contain a field id delta.
modifier := int16((t & 0xf0) >> 4)
if modifier == 0 {
// not a delta. look ahead for the zigzag varint field id.
id, err = p.ReadI16()
if err != nil {
return
}
} else {
// has a delta. add the delta to the last read field id.
id = int16(p.lastFieldIDRead) + modifier
}
typeId, e := p.getType(compactType(t & 0x0f))
if e != nil {
err = NewProtocolException(e)
return
}
// if this happens to be a boolean field, the value is encoded in the type
if p.isBoolType(t) {
// save the boolean value in a special instance variable.
p.boolValue = (byte(t)&0x0f == COMPACT_BOOLEAN_TRUE)
p.boolValueIsNotNull = true
}
// push the new field onto the field stack so we can keep the deltas going.
p.lastFieldIDRead = int(id)
return
} | Base | 1 |
func (m *ADeepBranch) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ADeepBranch: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ADeepBranch: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Down", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthThetest
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthThetest
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Down.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipThetest(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (m *OrderedFields) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowIssue42
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: OrderedFields: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: OrderedFields: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field B", wireType)
}
var v uint64
if (iNdEx + 8) > l {
return io.ErrUnexpectedEOF
}
v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:]))
iNdEx += 8
m.B = &v
case 10:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field A", wireType)
}
var v int64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowIssue42
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.A = &v
default:
iNdEx = preIndex
skippy, err := skipIssue42(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthIssue42
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthIssue42
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) {
params := k.GetParams(ctx)
expEpochID := k.GetEpochIdentifier(ctx)
if epochIdentifier != expEpochID {
return
}
// mint coins, update supply
epochMintProvision, found := k.GetEpochMintProvision(ctx)
if !found {
panic("the epochMintProvision was not found")
}
mintedCoin := sdk.NewCoin(params.MintDenom, epochMintProvision.TruncateInt())
if err := k.MintAndAllocateInflation(ctx, mintedCoin); err != nil {
panic(err)
}
// check if a period is over. If it's completed, update period, and epochMintProvision
period := k.GetPeriod(ctx)
epochsPerPeriod := k.GetEpochsPerPeriod(ctx)
newProvision := epochMintProvision
// current epoch number needs to be within range for the period
// Given, epochNumber = 1, period = 0, epochPerPeriod = 365
// 1 - 365 * 0 < 365 --- nothing to do here
// Given, epochNumber = 731, period = 1, epochPerPeriod = 365
// 731 - 1 * 365 > 365 --- a period has passed! we change the epochMintProvision and set a new period
if epochNumber-epochsPerPeriod*int64(period) > epochsPerPeriod {
period++
k.SetPeriod(ctx, period)
period = k.GetPeriod(ctx)
bondedRatio := k.stakingKeeper.BondedRatio(ctx)
newProvision = types.CalculateEpochMintProvision(
params,
period,
epochsPerPeriod,
bondedRatio,
)
k.SetEpochMintProvision(ctx, newProvision)
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeMint,
sdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprintf("%d", epochNumber)),
sdk.NewAttribute(types.AttributeKeyEpochProvisions, newProvision.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, mintedCoin.Amount.String()),
),
)
} | Class | 2 |
func (b *Backend) rxPacketHandler(c paho.Client, msg paho.Message) {
b.wg.Add(1)
defer b.wg.Done()
var uplinkFrame gw.UplinkFrame
t, err := marshaler.UnmarshalUplinkFrame(msg.Payload(), &uplinkFrame)
if err != nil {
log.WithFields(log.Fields{
"data_base64": base64.StdEncoding.EncodeToString(msg.Payload()),
}).WithError(err).Error("gateway/mqtt: unmarshal uplink frame error")
return
}
if uplinkFrame.TxInfo == nil {
log.WithFields(log.Fields{
"data_base64": base64.StdEncoding.EncodeToString(msg.Payload()),
}).Error("gateway/mqtt: tx_info must not be nil")
return
}
if uplinkFrame.RxInfo == nil {
log.WithFields(log.Fields{
"data_base64": base64.StdEncoding.EncodeToString(msg.Payload()),
}).Error("gateway/mqtt: rx_info must not be nil")
return
}
gatewayID := helpers.GetGatewayID(uplinkFrame.RxInfo)
b.setGatewayMarshaler(gatewayID, t)
uplinkID := helpers.GetUplinkID(uplinkFrame.RxInfo)
log.WithFields(log.Fields{
"uplink_id": uplinkID,
"gateway_id": gatewayID,
}).Info("gateway/mqtt: uplink frame received")
// Since with MQTT all subscribers will receive the uplink messages sent
// by all the gateways, the first instance receiving the message must lock it,
// so that other instances can ignore the same message (from the same gw).
key := fmt.Sprintf("lora:ns:uplink:lock:%s:%d:%d:%d:%s", gatewayID, uplinkFrame.TxInfo.Frequency, uplinkFrame.RxInfo.Board, uplinkFrame.RxInfo.Antenna, hex.EncodeToString(uplinkFrame.PhyPayload))
if locked, err := b.isLocked(key); err != nil || locked {
if err != nil {
log.WithError(err).WithFields(log.Fields{
"uplink_id": uplinkID,
"key": key,
}).Error("gateway/mqtt: acquire lock error")
}
return
}
b.rxPacketChan <- uplinkFrame
} | Class | 2 |
func (*MatchStateRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{32}
} | Base | 1 |
func (c *Client) Update() (data.TargetFiles, error) {
if err := c.UpdateRoots(); err != nil {
if _, ok := err.(verify.ErrExpired); ok {
// For backward compatibility, we wrap the ErrExpired inside
// ErrDecodeFailed.
return nil, ErrDecodeFailed{"root.json", err}
}
return nil, err
}
// Get timestamp.json, extract snapshot.json file meta and save the
// timestamp.json locally
timestampJSON, err := c.downloadMetaUnsafe("timestamp.json", defaultTimestampDownloadLimit)
if err != nil {
return nil, err
}
snapshotMeta, err := c.decodeTimestamp(timestampJSON)
if err != nil {
return nil, err
}
if err := c.local.SetMeta("timestamp.json", timestampJSON); err != nil {
return nil, err
}
// Get snapshot.json, then extract file metas.
// root.json meta should not be stored in the snapshot, if it is,
// the root will be checked, re-downloaded
snapshotJSON, err := c.downloadMetaFromTimestamp("snapshot.json", snapshotMeta)
if err != nil {
return nil, err
}
snapshotMetas, err := c.decodeSnapshot(snapshotJSON)
if err != nil {
return nil, err
}
// Save the snapshot.json
if err := c.local.SetMeta("snapshot.json", snapshotJSON); err != nil {
return nil, err
}
// If we don't have the targets.json, download it, determine updated
// targets and save targets.json in local storage
var updatedTargets data.TargetFiles
targetsMeta := snapshotMetas["targets.json"]
if !c.hasMetaFromSnapshot("targets.json", targetsMeta) {
targetsJSON, err := c.downloadMetaFromSnapshot("targets.json", targetsMeta)
if err != nil {
return nil, err
}
updatedTargets, err = c.decodeTargets(targetsJSON)
if err != nil {
return nil, err
}
if err := c.local.SetMeta("targets.json", targetsJSON); err != nil {
return nil, err
}
}
return updatedTargets, nil
} | Base | 1 |
func (*LeaderboardRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{25}
} | Base | 1 |
func Token(user model.TableUser) (string, error) {
tNow := time.Now()
tUTC := tNow
newTUTC := tUTC.Add(time.Duration(TokenExpiryTime) * time.Minute)
// Set custom claims
claims := &JwtUserClaim{
user.UserName,
user.IsAdmin,
user.UserGroup,
user.ExternalAuth,
user.ExternalProfile,
user.FirstName + " " + user.LastName,
user.Avatar,
jwt.StandardClaims{
ExpiresAt: newTUTC.Unix(),
},
}
logger.Debug("Current time : ", tNow)
logger.Debug("Local time : ", tUTC)
logger.Debug("Expire Local time : ", newTUTC)
// Create token with claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(JwtSecret))
if err != nil {
return "", err
}
return t, nil
} | Base | 1 |
func (b *Builder) buildMetricsHTTPConnectionManagerFilter() (*envoy_config_listener_v3.Filter, error) {
rc, err := b.buildRouteConfiguration("metrics", []*envoy_config_route_v3.VirtualHost{{
Name: "metrics",
Domains: []string{"*"},
Routes: []*envoy_config_route_v3.Route{{
Name: "metrics",
Match: &envoy_config_route_v3.RouteMatch{
PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: "/"},
},
Action: &envoy_config_route_v3.Route_Route{
Route: &envoy_config_route_v3.RouteAction{
ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
Cluster: "pomerium-control-plane-http",
},
},
},
}},
}})
if err != nil {
return nil, err
}
tc := marshalAny(&envoy_http_connection_manager.HttpConnectionManager{
CodecType: envoy_http_connection_manager.HttpConnectionManager_AUTO,
StatPrefix: "metrics",
RouteSpecifier: &envoy_http_connection_manager.HttpConnectionManager_RouteConfig{
RouteConfig: rc,
},
HttpFilters: []*envoy_http_connection_manager.HttpFilter{{
Name: "envoy.filters.http.router",
}},
})
return &envoy_config_listener_v3.Filter{
Name: "envoy.filters.network.http_connection_manager",
ConfigType: &envoy_config_listener_v3.Filter_TypedConfig{
TypedConfig: tc,
},
}, nil
} | Class | 2 |
func isMatchingRedirectURI(uri string, haystack []string) bool {
requested, err := url.Parse(uri)
if err != nil {
return false
}
for _, b := range haystack {
if strings.ToLower(b) == strings.ToLower(uri) || isLoopbackURI(requested, b) {
return true
}
}
return false
} | Base | 1 |
func (x *ListGroupsRequest) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[27]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | Base | 1 |
func (m *BytesValue) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowWrappers
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: BytesValue: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: BytesValue: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowWrappers
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthWrappers
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthWrappers
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
if m.Value == nil {
m.Value = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipWrappers(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthWrappers
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthWrappers
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (x *WalletLedger) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[42]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | Base | 1 |
func (*Config) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{14}
} | Base | 1 |
func (svc *Service) DeleteGlobalScheduledQueries(ctx context.Context, id uint) error {
if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionWrite); err != nil {
return err
}
return svc.DeleteScheduledQuery(ctx, id)
} | Class | 2 |
static bool anal_fcn_data (RCore *core, const char *input) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
ut32 fcn_size = r_anal_function_size_from_entry (fcn);
if (fcn) {
int i;
bool gap = false;
ut64 gap_addr = UT64_MAX;
char *bitmap = calloc (1, fcn_size);
if (bitmap) {
RAnalBlock *b;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, b) {
int f = b->addr - fcn->addr;
int t = R_MIN (f + b->size, fcn_size);
if (f >= 0) {
while (f < t) {
bitmap[f++] = 1;
}
}
}
}
for (i = 0; i < fcn_size; i++) {
ut64 here = fcn->addr + i;
if (bitmap && bitmap[i]) {
if (gap) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", here - gap_addr, gap_addr);
gap = false;
}
gap_addr = UT64_MAX;
} else {
if (!gap) {
gap = true;
gap_addr = here;
}
}
}
if (gap) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", fcn->addr + fcn_size - gap_addr, gap_addr);
}
free (bitmap);
return true;
}
return false;
} | Base | 1 |
func (svc Service) DeleteTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint) error {
if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {
return err
}
return svc.ds.DeleteScheduledQuery(ctx, scheduledQueryID)
} | Class | 2 |
func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, messageSockPair, logFilePair filePair) (*initProcess, error) {
cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initStandard))
nsMaps := make(map[configs.NamespaceType]string)
for _, ns := range c.config.Namespaces {
if ns.Path != "" {
nsMaps[ns.Type] = ns.Path
}
}
_, sharePidns := nsMaps[configs.NEWPID]
data, err := c.bootstrapData(c.config.Namespaces.CloneFlags(), nsMaps)
if err != nil {
return nil, err
}
init := &initProcess{
cmd: cmd,
messageSockPair: messageSockPair,
logFilePair: logFilePair,
manager: c.cgroupManager,
intelRdtManager: c.intelRdtManager,
config: c.newInitConfig(p),
container: c,
process: p,
bootstrapData: data,
sharePidns: sharePidns,
}
c.initProcess = init
return init, nil
} | Base | 1 |
func NewFositeMemoryStore(
r InternalRegistry,
c Configuration,
) *FositeMemoryStore {
return &FositeMemoryStore{
AuthorizeCodes: make(map[string]authorizeCode),
IDSessions: make(map[string]fosite.Requester),
AccessTokens: make(map[string]fosite.Requester),
PKCES: make(map[string]fosite.Requester),
RefreshTokens: make(map[string]fosite.Requester),
c: c,
r: r,
}
} | Base | 1 |
func (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string) (*AuthenticatorOAuth2IntrospectionResult, bool) {
if !config.Cache.Enabled {
return nil, false
}
item, found := a.tokenCache.Get(token)
if !found {
return nil, false
}
i := item.(*AuthenticatorOAuth2IntrospectionResult)
expires := time.Unix(i.Expires, 0)
if expires.Before(time.Now()) {
a.tokenCache.Del(token)
return nil, false
}
return i, true
} | Class | 2 |
func HTTP(c *HTTPContext) {
for _, route := range routes {
reqPath := strings.ToLower(c.Req.URL.Path)
m := route.re.FindStringSubmatch(reqPath)
if m == nil {
continue
}
// We perform check here because route matched in cmd/web.go is wider than needed,
// but we only want to output this message only if user is really trying to access
// Git HTTP endpoints.
if conf.Repository.DisableHTTPGit {
c.Error(http.StatusForbidden, "Interacting with repositories by HTTP protocol is disabled")
return
}
if route.method != c.Req.Method {
c.NotFound()
return
}
file := strings.TrimPrefix(reqPath, m[1]+"/")
dir, err := getGitRepoPath(m[1])
if err != nil {
log.Warn("HTTP.getGitRepoPath: %v", err)
c.NotFound()
return
}
route.handler(serviceHandler{
w: c.Resp,
r: c.Req.Request,
dir: dir,
file: file,
authUser: c.AuthUser,
ownerName: c.OwnerName,
ownerSalt: c.OwnerSalt,
repoID: c.RepoID,
repoName: c.RepoName,
})
return
}
c.NotFound()
} | Base | 1 |
func (m *Unrecognized) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Unrecognized: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Unrecognized: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthThetest
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthThetest
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
s := string(dAtA[iNdEx:postIndex])
m.Field1 = &s
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipThetest(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func generateDataset(dest []uint32, epoch uint64, cache []uint32) {
// Print some debug logs to allow analysis on low end devices
logger := log.New("epoch", epoch)
start := time.Now()
defer func() {
elapsed := time.Since(start)
logFn := logger.Debug
if elapsed > 3*time.Second {
logFn = logger.Info
}
logFn("Generated ethash verification cache", "elapsed", common.PrettyDuration(elapsed))
}()
// Figure out whether the bytes need to be swapped for the machine
swapped := !isLittleEndian()
// Convert our destination slice to a byte buffer
header := *(*reflect.SliceHeader)(unsafe.Pointer(&dest))
header.Len *= 4
header.Cap *= 4
dataset := *(*[]byte)(unsafe.Pointer(&header))
// Generate the dataset on many goroutines since it takes a while
threads := runtime.NumCPU()
size := uint64(len(dataset))
var pend sync.WaitGroup
pend.Add(threads)
var progress uint64
for i := 0; i < threads; i++ {
go func(id int) {
defer pend.Done()
// Create a hasher to reuse between invocations
keccak512 := makeHasher(sha3.NewLegacyKeccak512())
// Calculate the data segment this thread should generate
batch := uint32((size + hashBytes*uint64(threads) - 1) / (hashBytes * uint64(threads)))
first := uint32(id) * batch
limit := first + batch
if limit > uint32(size/hashBytes) {
limit = uint32(size / hashBytes)
}
// Calculate the dataset segment
percent := size / hashBytes / 100
for index := first; index < limit; index++ {
item := generateDatasetItem(cache, index, keccak512)
if swapped {
swap(item)
}
copy(dataset[index*hashBytes:], item)
if status := atomic.AddUint64(&progress, 1); status%percent == 0 {
logger.Info("Generating DAG in progress", "percentage", (status*100)/(size/hashBytes), "elapsed", common.PrettyDuration(time.Since(start)))
}
}
}(i)
}
// Wait for all the generators to finish and return
pend.Wait()
} | Pillar | 3 |
func (m *StringValue) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowWrappers
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: StringValue: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: StringValue: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowWrappers
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthWrappers
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthWrappers
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Value = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipWrappers(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthWrappers
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthWrappers
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (m *Aproto3) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProto3
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Aproto3: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Aproto3: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field B", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProto3
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthProto3
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthProto3
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.B = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProto3(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProto3
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthProto3
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (p *GitLabProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {
// Retrieve user info
userInfo, err := p.getUserInfo(ctx, s)
if err != nil {
return fmt.Errorf("failed to retrieve user info: %v", err)
}
// Check if email is verified
if !p.AllowUnverifiedEmail && !userInfo.EmailVerified {
return fmt.Errorf("user email is not verified")
}
s.User = userInfo.Username
s.Email = userInfo.Email
p.addGroupsToSession(ctx, s)
p.addProjectsToSession(ctx, s)
return nil
} | Class | 2 |
func (x *DeleteFriendRequest) Reset() {
*x = DeleteFriendRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | Base | 1 |
getReturnAddressWithDisplayName(identityId) {
check(identityId, String);
const identity = this.getIdentity(identityId);
const displayName = identity.profile.name + " (via " + this.getServerTitle() + ")";
// First remove any instances of characters that cause trouble for SimpleSmtp. Ideally,
// we could escape such characters with a backslash, but that does not seem to help here.
const sanitized = displayName.replace(/"|<|>|\\|\r/g, "");
return "\"" + sanitized + "\" <" + this.getReturnAddress() + ">";
}, | Class | 2 |
func NewReader(src io.Reader, size int64, md5Hex, sha256Hex string) (*Reader, error) {
if _, ok := src.(*Reader); ok {
return nil, errNestedReader
}
sha256sum, err := hex.DecodeString(sha256Hex)
if err != nil {
return nil, SHA256Mismatch{}
}
md5sum, err := hex.DecodeString(md5Hex)
if err != nil {
return nil, BadDigest{}
}
var sha256Hash hash.Hash
if len(sha256sum) != 0 {
sha256Hash = sha256.New()
}
return &Reader{
md5sum: md5sum,
sha256sum: sha256sum,
src: io.LimitReader(src, size),
size: size,
md5Hash: md5.New(),
sha256Hash: sha256Hash,
}, nil
} | Variant | 0 |
func UnpackTar(filename string, destination string, verbosityLevel int) (err error) {
Verbose = verbosityLevel
f, err := os.Stat(destination)
if os.IsNotExist(err) {
return fmt.Errorf("destination directory '%s' does not exist", destination)
}
filemode := f.Mode()
if !filemode.IsDir() {
return fmt.Errorf("destination '%s' is not a directory", destination)
}
if !validSuffix(filename) {
return fmt.Errorf("unrecognized archive suffix")
}
var file *os.File
// #nosec G304
if file, err = os.Open(filename); err != nil {
return err
}
defer file.Close()
err = os.Chdir(destination)
if err != nil {
return errors.Wrapf(err, "error changing directory to %s", destination)
}
var fileReader io.Reader = file
var decompressor *gzip.Reader
if strings.HasSuffix(filename, globals.GzExt) {
if decompressor, err = gzip.NewReader(file); err != nil {
return err
}
defer decompressor.Close()
}
var reader *tar.Reader
if decompressor != nil {
reader = tar.NewReader(decompressor)
} else {
reader = tar.NewReader(fileReader)
}
return unpackTarFiles(reader)
} | Base | 1 |
func (net *Network) checkTopicRegister(data *topicRegister) (*pong, error) {
var pongpkt ingressPacket
if err := decodePacket(data.Pong, &pongpkt); err != nil {
return nil, err
}
if pongpkt.ev != pongPacket {
return nil, errors.New("is not pong packet")
}
if pongpkt.remoteID != net.tab.self.ID {
return nil, errors.New("not signed by us")
}
// check that we previously authorised all topics
// that the other side is trying to register.
hash, _, _ := wireHash(data.Topics)
if hash != pongpkt.data.(*pong).TopicHash {
return nil, errors.New("topic hash mismatch")
}
if data.Idx < 0 || int(data.Idx) >= len(data.Topics) {
return nil, errors.New("topic index out of range")
}
return pongpkt.data.(*pong), nil
} | Base | 1 |
func (a *AuthenticatorOAuth2Introspection) tokenToCache(config *AuthenticatorOAuth2IntrospectionConfiguration, i *AuthenticatorOAuth2IntrospectionResult, token string) {
if !config.Cache.Enabled {
return
}
if a.cacheTTL != nil {
a.tokenCache.SetWithTTL(token, i, 1, *a.cacheTTL)
} else {
a.tokenCache.Set(token, i, 1)
}
} | Class | 2 |
func TestDoesPolicySignatureMatch(t *testing.T) {
credentialTemplate := "%s/%s/%s/s3/aws4_request"
now := UTCNow()
accessKey := globalActiveCred.AccessKey
testCases := []struct {
form http.Header
expected APIErrorCode
}{
// (0) It should fail if 'X-Amz-Credential' is missing.
{
form: http.Header{},
expected: ErrCredMalformed,
},
// (1) It should fail if the access key is incorrect.
{
form: http.Header{
"X-Amz-Credential": []string{fmt.Sprintf(credentialTemplate, "EXAMPLEINVALIDEXAMPL", now.Format(yyyymmdd), globalMinioDefaultRegion)},
},
expected: ErrInvalidAccessKeyID,
},
// (2) It should fail with a bad signature.
{
form: http.Header{
"X-Amz-Credential": []string{fmt.Sprintf(credentialTemplate, accessKey, now.Format(yyyymmdd), globalMinioDefaultRegion)},
"X-Amz-Date": []string{now.Format(iso8601Format)},
"X-Amz-Signature": []string{"invalidsignature"},
"Policy": []string{"policy"},
},
expected: ErrSignatureDoesNotMatch,
},
// (3) It should succeed if everything is correct.
{
form: http.Header{
"X-Amz-Credential": []string{
fmt.Sprintf(credentialTemplate, accessKey, now.Format(yyyymmdd), globalMinioDefaultRegion),
},
"X-Amz-Date": []string{now.Format(iso8601Format)},
"X-Amz-Signature": []string{
getSignature(getSigningKey(globalActiveCred.SecretKey, now,
globalMinioDefaultRegion, serviceS3), "policy"),
},
"Policy": []string{"policy"},
},
expected: ErrNone,
},
}
// Run each test case individually.
for i, testCase := range testCases {
code := doesPolicySignatureMatch(testCase.form)
if code != testCase.expected {
t.Errorf("(%d) expected to get %s, instead got %s", i, niceError(testCase.expected), niceError(code))
}
}
} | Class | 2 |
func (m *ProtoType) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ProtoType: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ProtoType: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Field2", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthThetest
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthThetest
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
s := string(dAtA[iNdEx:postIndex])
m.Field2 = &s
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipThetest(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func TestClean(t *testing.T) {
tests := []struct {
path string
expVal string
}{
{
path: "../../../readme.txt",
expVal: "readme.txt",
},
{
path: "a/../../../readme.txt",
expVal: "readme.txt",
},
{
path: "/../a/b/../c/../readme.txt",
expVal: "a/readme.txt",
},
{
path: "/a/readme.txt",
expVal: "a/readme.txt",
},
{
path: "/",
expVal: "",
},
{
path: "/a/b/c/readme.txt",
expVal: "a/b/c/readme.txt",
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.expVal, Clean(test.path))
})
}
} | Base | 1 |
func (g Grant) ValidateBasic() error {
if g.Expiration.Unix() < time.Now().Unix() {
return sdkerrors.Wrap(ErrInvalidExpirationTime, "Time can't be in the past")
}
av := g.Authorization.GetCachedValue()
a, ok := av.(Authorization)
if !ok {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expected %T, got %T", (Authorization)(nil), av)
}
return a.ValidateBasic()
} | Class | 2 |
func (m *NinOptNonByteCustomType) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: NinOptNonByteCustomType: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: NinOptNonByteCustomType: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthThetest
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthThetest
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Field1 == nil {
m.Field1 = &T{}
}
if err := m.Field1.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipThetest(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (*RuntimeInfo_ModuleInfo) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{41, 0}
} | Base | 1 |
func SearchUserByName(opt SearchOption) (us []*User, err error) {
// Prevent SQL inject.
opt.Keyword = strings.TrimSpace(opt.Keyword)
if len(opt.Keyword) == 0 {
return us, nil
}
opt.Keyword = strings.Split(opt.Keyword, " ")[0]
if len(opt.Keyword) == 0 {
return us, nil
}
opt.Keyword = strings.ToLower(opt.Keyword)
us = make([]*User, 0, opt.Limit)
err = x.Limit(opt.Limit).Where("type=0").And("lower_name like '%" + opt.Keyword + "%'").Find(&us)
return us, err
} | Base | 1 |
func isMatchingRedirectURI(uri string, haystack []string) bool {
requested, err := url.Parse(uri)
if err != nil {
return false
}
for _, b := range haystack {
if strings.ToLower(b) == strings.ToLower(uri) || isLoopbackURI(requested, b) {
return true
}
}
return false
} | Base | 1 |
func (m *UnrecognizedWithEmbed_Embedded) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Embedded: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Embedded: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType)
}
var v uint32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= uint32(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Field1 = &v
default:
iNdEx = preIndex
skippy, err := skipThetest(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func Test_buildControlPlanePrefixRoute(t *testing.T) {
b := &Builder{filemgr: filemgr.NewManager()}
route, err := b.buildControlPlanePrefixRoute("/hello/world/", false)
require.NoError(t, err)
testutil.AssertProtoJSONEqual(t, `
{
"name": "pomerium-prefix-/hello/world/",
"match": {
"prefix": "/hello/world/"
},
"route": {
"cluster": "pomerium-control-plane-http"
},
"typedPerFilterConfig": {
"envoy.filters.http.ext_authz": {
"@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute",
"disabled": true
}
}
}
`, route)
} | Class | 2 |
appendMessage = func(targetOffset uint32) bool {
for _, f := range frags {
if f.handshakeHeader.FragmentOffset == targetOffset {
fragmentEnd := (f.handshakeHeader.FragmentOffset + f.handshakeHeader.FragmentLength)
if fragmentEnd != f.handshakeHeader.Length {
if !appendMessage(fragmentEnd) {
return false
}
}
rawMessage = append(f.data, rawMessage...)
return true
}
}
return false
} | Base | 1 |
func DeleteCode(id string) {
delete(memory.Code, id)
} | Base | 1 |
func TestBuilder_BuildBootstrapStatsConfig(t *testing.T) {
b := New("local-grpc", "local-http", filemgr.NewManager(), nil)
t.Run("valid", func(t *testing.T) {
statsCfg, err := b.BuildBootstrapStatsConfig(&config.Config{
Options: &config.Options{
Services: "all",
},
})
assert.NoError(t, err)
testutil.AssertProtoJSONEqual(t, `
{
"statsTags": [{
"tagName": "service",
"fixedValue": "pomerium"
}]
}
`, statsCfg)
})
} | Class | 2 |
func (f *Fosite) WriteAuthorizeError(rw http.ResponseWriter, ar AuthorizeRequester, err error) {
rw.Header().Set("Cache-Control", "no-store")
rw.Header().Set("Pragma", "no-cache")
rfcerr := ErrorToRFC6749Error(err)
if !f.SendDebugMessagesToClients {
rfcerr = rfcerr.Sanitize()
}
if !ar.IsRedirectURIValid() {
rw.Header().Set("Content-Type", "application/json;charset=UTF-8")
js, err := json.Marshal(rfcerr)
if err != nil {
if f.SendDebugMessagesToClients {
errorMessage := EscapeJSONString(err.Error())
http.Error(rw, fmt.Sprintf(`{"error":"server_error","error_description":"%s"}`, errorMessage), http.StatusInternalServerError)
} else {
http.Error(rw, `{"error":"server_error"}`, http.StatusInternalServerError)
}
return
}
rw.WriteHeader(rfcerr.Code)
rw.Write(js)
return
}
redirectURI := ar.GetRedirectURI()
// The endpoint URI MUST NOT include a fragment component.
redirectURI.Fragment = ""
query := rfcerr.ToValues()
query.Add("state", ar.GetState())
var redirectURIString string
if !(len(ar.GetResponseTypes()) == 0 || ar.GetResponseTypes().ExactOne("code")) && !errors.Is(err, ErrUnsupportedResponseType) {
redirectURIString = redirectURI.String() + "#" + query.Encode()
} else {
for key, values := range redirectURI.Query() {
for _, value := range values {
query.Add(key, value)
}
}
redirectURI.RawQuery = query.Encode()
redirectURIString = redirectURI.String()
}
rw.Header().Add("Location", redirectURIString)
rw.WriteHeader(http.StatusFound)
} | Class | 2 |
func (x *UpdateAccountRequest) Reset() {
*x = UpdateAccountRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[36]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | Base | 1 |
func (svc Service) ModifyTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint, query fleet.ScheduledQueryPayload) (*fleet.ScheduledQuery, error) {
if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {
return nil, err
}
gp, err := svc.ds.EnsureTeamPack(ctx, teamID)
if err != nil {
return nil, err
}
query.PackID = ptr.Uint(gp.ID)
return svc.unauthorizedModifyScheduledQuery(ctx, scheduledQueryID, query)
} | Class | 2 |
func (m *CustomDash) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: CustomDash: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: CustomDash: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowThetest
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthThetest
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthThetest
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
var v github_com_gogo_protobuf_test_custom_dash_type.Bytes
m.Value = &v
if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipThetest(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthThetest
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (m *Subby) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Subby: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Subby: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Sub", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthOne
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthOne
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
s := string(dAtA[iNdEx:postIndex])
m.Sub = &s
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipOne(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthOne
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthOne
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func createDeviceNode(rootfs string, node *devices.Device, bind bool) error {
if node.Path == "" {
// The node only exists for cgroup reasons, ignore it here.
return nil
}
dest := filepath.Join(rootfs, node.Path)
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return err
}
if bind {
return bindMountDeviceNode(dest, node)
}
if err := mknodDevice(dest, node); err != nil {
if os.IsExist(err) {
return nil
} else if os.IsPermission(err) {
return bindMountDeviceNode(dest, node)
}
return err
}
return nil
} | Class | 2 |
func (m *FloatValue) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowWrappers
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: FloatValue: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: FloatValue: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
var v uint32
if (iNdEx + 4) > l {
return io.ErrUnexpectedEOF
}
v = uint32(encoding_binary.LittleEndian.Uint32(dAtA[iNdEx:]))
iNdEx += 4
m.Value = float32(math.Float32frombits(v))
default:
iNdEx = preIndex
skippy, err := skipWrappers(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthWrappers
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthWrappers
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (x *StorageList) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[33]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | Base | 1 |
func (x *RuntimeInfo) Reset() {
*x = RuntimeInfo{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[41]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | Base | 1 |
func (*CallApiEndpointResponse) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{13}
} | Base | 1 |
func (p *GitLabProvider) addGroupsToSession(ctx context.Context, s *sessions.SessionState) {
// Iterate over projects, check if oauth2-proxy can get project information on behalf of the user
for _, group := range p.Groups {
s.Groups = append(s.Groups, fmt.Sprintf("group:%s", group))
}
} | Class | 2 |
func (hs *HTTPServer) pluginMarkdown(ctx context.Context, pluginId string, name string) ([]byte, error) {
plugin, exists := hs.pluginStore.Plugin(ctx, pluginId)
if !exists {
return nil, plugins.NotFoundError{PluginID: pluginId}
}
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based
// on plugin the folder structure on disk and not user input.
path := filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToUpper(name)))
exists, err := fs.Exists(path)
if err != nil {
return nil, err
}
if !exists {
path = filepath.Join(plugin.PluginDir, fmt.Sprintf("%s.md", strings.ToLower(name)))
}
exists, err = fs.Exists(path)
if err != nil {
return nil, err
}
if !exists {
return make([]byte, 0), nil
}
// nolint:gosec
// We can ignore the gosec G304 warning on this one because `plugin.PluginDir` is based
// on plugin the folder structure on disk and not user input.
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return data, nil
} | Base | 1 |
func (p *CompactProtocol) ReadBinary() (value []byte, err error) {
length, e := p.readVarint32()
if e != nil {
return nil, NewProtocolException(e)
}
if length == 0 {
return []byte{}, nil
}
if length < 0 {
return nil, invalidDataLength
}
if uint64(length) > p.trans.RemainingBytes() {
return nil, invalidDataLength
}
buf := make([]byte, length)
_, e = io.ReadFull(p.trans, buf)
return buf, NewProtocolException(e)
} | Base | 1 |
func (x *LeaderboardRequest) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[25]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | Base | 1 |
func Skip(self Protocol, fieldType Type, maxDepth int) (err error) {
if maxDepth <= 0 {
return NewProtocolExceptionWithType(DEPTH_LIMIT, errors.New("Depth limit exceeded"))
}
switch fieldType {
case STOP:
return
case BOOL:
_, err = self.ReadBool()
return
case BYTE:
_, err = self.ReadByte()
return
case I16:
_, err = self.ReadI16()
return
case I32:
_, err = self.ReadI32()
return
case I64:
_, err = self.ReadI64()
return
case DOUBLE:
_, err = self.ReadDouble()
return
case FLOAT:
_, err = self.ReadFloat()
return
case STRING:
_, err = self.ReadString()
return
case STRUCT:
if _, err = self.ReadStructBegin(); err != nil {
return err
}
for {
_, typeId, _, _ := self.ReadFieldBegin()
if typeId == STOP {
break
}
err := Skip(self, typeId, maxDepth-1)
if err != nil {
return err
}
self.ReadFieldEnd()
}
return self.ReadStructEnd()
case MAP:
keyType, valueType, size, err := self.ReadMapBegin()
if err != nil {
return err
}
for i := 0; i < size; i++ {
err := Skip(self, keyType, maxDepth-1)
if err != nil {
return err
}
self.Skip(valueType)
}
return self.ReadMapEnd()
case SET:
elemType, size, err := self.ReadSetBegin()
if err != nil {
return err
}
for i := 0; i < size; i++ {
err := Skip(self, elemType, maxDepth-1)
if err != nil {
return err
}
}
return self.ReadSetEnd()
case LIST:
elemType, size, err := self.ReadListBegin()
if err != nil {
return err
}
for i := 0; i < size; i++ {
err := Skip(self, elemType, maxDepth-1)
if err != nil {
return err
}
}
return self.ReadListEnd()
}
return nil
} | Class | 2 |
func TestInvalidPaddingOpen(t *testing.T) {
key := make([]byte, 32)
nonce := make([]byte, 16)
// Plaintext with invalid padding
plaintext := padBuffer(make([]byte, 28), aes.BlockSize)
plaintext[len(plaintext)-1] = 0xFF
io.ReadFull(rand.Reader, key)
io.ReadFull(rand.Reader, nonce)
block, _ := aes.NewCipher(key)
cbc := cipher.NewCBCEncrypter(block, nonce)
buffer := append([]byte{}, plaintext...)
cbc.CryptBlocks(buffer, buffer)
aead, _ := NewCBCHMAC(key, aes.NewCipher)
ctx := aead.(*cbcAEAD)
// Mutated ciphertext, but with correct auth tag
size := len(buffer)
ciphertext, tail := resize(buffer, size+(len(key)/2))
copy(tail, ctx.computeAuthTag(nil, nonce, ciphertext[:size]))
// Open should fail (b/c of invalid padding, even though tag matches)
_, err := aead.Open(nil, nonce, ciphertext, nil)
if err == nil || !strings.Contains(err.Error(), "invalid padding") {
t.Error("no or unexpected error on open with invalid padding:", err)
}
} | Base | 1 |
func (h *Handler) DefaultErrorHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
h.L.Warnln("A client requested the default error URL, environment variable OAUTH2_ERROR_URL is probably not set.")
fmt.Fprintf(w, `
<html>
<head>
<title>An OAuth 2.0 Error Occurred</title>
</head>
<body>
<h1>
The OAuth2 request resulted in an error.
</h1>
<ul>
<li>Error: %s</li>
<li>Description: %s</li>
<li>Hint: %s</li>
<li>Debug: %s</li>
</ul>
<p>
You are seeing this default error page because the administrator has not set a dedicated error URL (environment variable <code>OAUTH2_ERROR_URL</code> is not set).
If you are an administrator, please read <a href="https://www.ory.sh/docs">the guide</a> to understand what you
need to do. If you are a user, please contact the administrator.
</p>
</body>
</html>
`, r.URL.Query().Get("error"), r.URL.Query().Get("error_description"), r.URL.Query().Get("error_hint"), r.URL.Query().Get("error_debug"))
} | Base | 1 |
private HandshakeMessage createClientHandshakeMessage(
HandshakeType type, byte[] buffer)
{
switch (type)
{
case HandshakeType.ClientHello:
return new TlsClientHello(this.context, buffer);
case HandshakeType.Certificate:
return new TlsClientCertificate(this.context, buffer);
case HandshakeType.ClientKeyExchange:
return new TlsClientKeyExchange(this.context, buffer);
case HandshakeType.CertificateVerify:
return new TlsClientCertificateVerify(this.context, buffer);
case HandshakeType.Finished:
return new TlsClientFinished(this.context, buffer);
default:
throw new TlsException(
AlertDescription.UnexpectedMessage,
String.Format(CultureInfo.CurrentUICulture,
"Unknown server handshake message received ({0})",
type.ToString()));
}
} | Base | 1 |
func (x *UnlinkDeviceRequest) Reset() {
*x = UnlinkDeviceRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[35]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | Base | 1 |
func (p *HTTPClient) RemainingBytes() (num_bytes uint64) {
len := p.response.ContentLength
if len >= 0 {
return uint64(len)
}
return UnknownRemaining // the truth is, we just don't know unless framed is used
} | Base | 1 |
func TestMsgGrantAuthorization(t *testing.T) {
tests := []struct {
title string
granter, grantee sdk.AccAddress
authorization authz.Authorization
expiration time.Time
expectErr bool
expectPass bool
}{
{"nil granter address", nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
{"nil grantee address", granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
{"nil granter and grantee address", nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},
{"nil authorization", granter, grantee, nil, time.Now(), true, false},
{"valid test case", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 1, 0), false, true},
{"past time", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 0, -1), false, false},
}
for i, tc := range tests {
msg, err := authz.NewMsgGrant(
tc.granter, tc.grantee, tc.authorization, tc.expiration,
)
if !tc.expectErr {
require.NoError(t, err)
} else {
continue
}
if tc.expectPass {
require.NoError(t, msg.ValidateBasic(), "test: %v", i)
} else {
require.Error(t, msg.ValidateBasic(), "test: %v", i)
}
}
} | Class | 2 |
func cmdGet(args *docopt.Args, client *tuf.Client) error {
if _, err := client.Update(); err != nil && !tuf.IsLatestSnapshot(err) {
return err
}
target := util.NormalizeTarget(args.String["<target>"])
file, err := ioutil.TempFile("", "go-tuf")
if err != nil {
return err
}
tmp := tmpFile{file}
if err := client.Download(target, &tmp); err != nil {
return err
}
defer tmp.Delete()
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return err
}
_, err = io.Copy(os.Stdout, file)
return err
} | Base | 1 |
func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sortType string) ([]Issue, error) {
sess := x.Limit(20, (page-1)*20)
if rid > 0 {
sess.Where("repo_id=?", rid).And("is_closed=?", isClosed)
} else {
sess.Where("is_closed=?", isClosed)
}
if uid > 0 {
sess.And("assignee_id=?", uid)
} else if pid > 0 {
sess.And("poster_id=?", pid)
}
if mid > 0 {
sess.And("milestone_id=?", mid)
}
if len(labelIds) > 0 {
for _, label := range strings.Split(labelIds, ",") {
sess.And("label_ids like '%$" + label + "|%'")
}
}
switch sortType {
case "oldest":
sess.Asc("created")
case "recentupdate":
sess.Desc("updated")
case "leastupdate":
sess.Asc("updated")
case "mostcomment":
sess.Desc("num_comments")
case "leastcomment":
sess.Asc("num_comments")
case "priority":
sess.Desc("priority")
default:
sess.Desc("created")
}
var issues []Issue
err := sess.Find(&issues)
return issues, err
} | Base | 1 |
func validateWebhook(actor *db.User, l macaron.Locale, w *db.Webhook) (field, msg string, ok bool) {
if !actor.IsAdmin {
// 🚨 SECURITY: Local addresses must not be allowed by non-admins to prevent SSRF,
// see https://github.com/gogs/gogs/issues/5366 for details.
payloadURL, err := url.Parse(w.URL)
if err != nil {
return "PayloadURL", l.Tr("repo.settings.webhook.err_cannot_parse_payload_url", err), false
}
if netutil.IsLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) {
return "PayloadURL", l.Tr("repo.settings.webhook.err_cannot_use_local_addresses"), false
}
}
return "", "", true
} | Base | 1 |
func SanitizePath(path string) string {
return strings.TrimLeft(path, "./")
} | Base | 1 |
func (x *ListPurchasesRequest) Reset() {
*x = ListPurchasesRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[28]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | Base | 1 |
func (m *Foo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProto
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Foo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Foo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Bar", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProto
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthProto
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthProto
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Bar = append(m.Bar[:0], dAtA[iNdEx:postIndex]...)
if m.Bar == nil {
m.Bar = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProto(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProto
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthProto
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func logNamespaceDiagnostics(spec *specs.Spec) {
sawMountNS := false
sawUserNS := false
sawUTSNS := false
for _, ns := range spec.Linux.Namespaces {
switch ns.Type {
case specs.CgroupNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join cgroup namespace, sorry about that")
} else {
logrus.Debugf("unable to create cgroup namespace, sorry about that")
}
case specs.IPCNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join IPC namespace, sorry about that")
} else {
logrus.Debugf("unable to create IPC namespace, sorry about that")
}
case specs.MountNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join mount namespace %q, creating a new one", ns.Path)
}
sawMountNS = true
case specs.NetworkNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join network namespace, sorry about that")
} else {
logrus.Debugf("unable to create network namespace, sorry about that")
}
case specs.PIDNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join PID namespace, sorry about that")
} else {
logrus.Debugf("unable to create PID namespace, sorry about that")
}
case specs.UserNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join user namespace %q, creating a new one", ns.Path)
}
sawUserNS = true
case specs.UTSNamespace:
if ns.Path != "" {
logrus.Debugf("unable to join UTS namespace %q, creating a new one", ns.Path)
}
sawUTSNS = true
}
}
if !sawMountNS {
logrus.Debugf("mount namespace not requested, but creating a new one anyway")
}
if !sawUserNS {
logrus.Debugf("user namespace not requested, but creating a new one anyway")
}
if !sawUTSNS {
logrus.Debugf("UTS namespace not requested, but creating a new one anyway")
}
} | Class | 2 |
func generateHMAC(data []byte, key *[32]byte) []byte {
h := hmac.New(sha512.New512_256, key[:])
h.Write(data)
return h.Sum(nil)
} | Class | 2 |
func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
// Logic based on response type or status
if noBodyExpected(requestMethod) {
return 0, nil
}
if status/100 == 1 {
return 0, nil
}
switch status {
case 204, 304:
return 0, nil
}
// Logic based on Transfer-Encoding
if chunked(te) {
return -1, nil
}
// Logic based on Content-Length
cl := strings.TrimSpace(header.get("Content-Length"))
if cl != "" {
n, err := parseContentLength(cl)
if err != nil {
return -1, err
}
return n, nil
} else {
header.Del("Content-Length")
}
if !isResponse && requestMethod == "GET" {
// RFC 2616 doesn't explicitly permit nor forbid an
// entity-body on a GET request so we permit one if
// declared, but we default to 0 here (not -1 below)
// if there's no mention of a body.
return 0, nil
}
// Body-EOF logic based on other methods (like closing, or chunked coding)
return -1, nil
} | Base | 1 |
func TestEscapeJSONString(t *testing.T) {
for _, str := range []string{"", "foobar", `foo"bar`, `foo\bar`, "foo\n\tbar"} {
escaped := EscapeJSONString(str)
var unmarshaled string
err := json.Unmarshal([]byte(`"` + escaped + `"`), &unmarshaled)
require.NoError(t, err, str)
assert.Equal(t, str, unmarshaled, str)
}
} | Base | 1 |
func (m *Object) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowObject
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Object: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Object: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field OptionalNumber", wireType)
}
var v int64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowObject
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.OptionalNumber = &v
default:
iNdEx = preIndex
skippy, err := skipObject(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthObject
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthObject
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (*ConsoleSession) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{15}
} | Base | 1 |
func (*ListSubscriptionsRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{29}
} | Base | 1 |
return utils.WithProcfd(rootfs, m.Destination, func(procfd string) error {
return mount(m.Source, m.Destination, procfd, m.Device, uintptr(m.Flags|unix.MS_REMOUNT), "")
}) | Base | 1 |
func (svc *Service) ListHostDeviceMapping(ctx context.Context, id uint) ([]*fleet.HostDeviceMapping, error) {
if !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) {
if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
return nil, err
}
host, err := svc.ds.HostLite(ctx, id)
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "get host")
}
// Authorize again with team loaded now that we have team_id
if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
return nil, err
}
}
return svc.ds.ListHostDeviceMapping(ctx, id)
} | Class | 2 |
func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error {
hashes := make([][]byte, len(evList))
for idx, ev := range evList {
ok := evpool.fastCheck(ev)
if !ok {
// check that the evidence isn't already committed
if evpool.isCommitted(ev) {
return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("evidence was already committed")}
}
err := evpool.verify(ev)
if err != nil {
return &types.ErrInvalidEvidence{Evidence: ev, Reason: err}
}
if err := evpool.addPendingEvidence(ev); err != nil {
// Something went wrong with adding the evidence but we already know it is valid
// hence we log an error and continue
evpool.logger.Error("Can't add evidence to pending list", "err", err, "ev", ev)
}
evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)
}
// check for duplicate evidence. We cache hashes so we don't have to work them out again.
hashes[idx] = ev.Hash()
for i := idx - 1; i >= 0; i-- {
if bytes.Equal(hashes[i], hashes[idx]) {
return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("duplicate evidence")}
}
}
}
return nil
} | Class | 2 |
func newMockResourceServer(t testing.TB) ResourceServer {
ctx := context.Background()
dummy := ""
serverURL := &dummy
hf := func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/.well-known/oauth-authorization-server" {
w.Header().Set("Content-Type", "application/json")
_, err := io.WriteString(w, strings.ReplaceAll(`{
"issuer": "https://dev-14186422.okta.com",
"authorization_endpoint": "https://example.com/auth",
"token_endpoint": "https://example.com/token",
"jwks_uri": "URL/keys",
"id_token_signing_alg_values_supported": ["RS256"]
}`, "URL", *serverURL))
if !assert.NoError(t, err) {
t.FailNow()
}
return
} else if r.URL.Path == "/keys" {
keys := jwk.NewSet()
raw, err := json.Marshal(keys)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
w.Header().Set("Content-Type", "application/json")
_, err = io.WriteString(w, string(raw))
if !assert.NoError(t, err) {
t.FailNow()
}
}
http.NotFound(w, r)
}
s := httptest.NewServer(http.HandlerFunc(hf))
defer s.Close()
*serverURL = s.URL
http.DefaultClient = s.Client()
r, err := NewOAuth2ResourceServer(ctx, authConfig.ExternalAuthorizationServer{
BaseURL: stdlibConfig.URL{URL: *config.MustParseURL(s.URL)},
}, stdlibConfig.URL{})
if !assert.NoError(t, err) {
t.FailNow()
}
return r
} | Base | 1 |
func (EmptyEvidencePool) AddEvidence(types.Evidence) error { return nil } | Class | 2 |
func GetCode(id string) string {
return memory.Code[id]
} | Base | 1 |
func (m *MyType) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowAsym
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: MyType: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: MyType: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipAsym(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthAsym
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthAsym
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func (m *CastType) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowExample
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: CastType: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: CastType: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Int32", wireType)
}
var v int32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowExample
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Int32 = &v
default:
iNdEx = preIndex
skippy, err := skipExample(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthExample
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthExample
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
} | Variant | 0 |
func getClaimsFromToken(r *http.Request, token string) (map[string]interface{}, error) { | Class | 2 |
func checkAuth(ctx context.Context, config Config, auth string) (context.Context, bool) {
const basicPrefix = "Basic "
const bearerPrefix = "Bearer "
if strings.HasPrefix(auth, basicPrefix) {
// Basic authentication.
username, password, ok := parseBasicAuth(auth)
if !ok {
return ctx, false
}
if username != config.GetConsole().Username || password != config.GetConsole().Password {
// Username and/or password do not match.
return ctx, false
}
ctx = context.WithValue(context.WithValue(context.WithValue(ctx, ctxConsoleRoleKey{}, console.UserRole_USER_ROLE_ADMIN), ctxConsoleUsernameKey{}, username), ctxConsoleEmailKey{}, "")
// Basic authentication successful.
return ctx, true
} else if strings.HasPrefix(auth, bearerPrefix) {
// Bearer token authentication.
token, err := jwt.Parse(auth[len(bearerPrefix):], func(token *jwt.Token) (interface{}, error) {
if s, ok := token.Method.(*jwt.SigningMethodHMAC); !ok || s.Hash != crypto.SHA256 {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(config.GetConsole().SigningKey), nil
})
if err != nil {
// Token verification failed.
return ctx, false
}
uname, email, role, exp, ok := parseConsoleToken([]byte(config.GetConsole().SigningKey), auth[len(bearerPrefix):])
if !ok || !token.Valid {
// The token or its claims are invalid.
return ctx, false
}
if !ok {
// Expiry time claim is invalid.
return ctx, false
}
if exp <= time.Now().UTC().Unix() {
// Token expired.
return ctx, false
}
ctx = context.WithValue(context.WithValue(context.WithValue(ctx, ctxConsoleRoleKey{}, role), ctxConsoleUsernameKey{}, uname), ctxConsoleEmailKey{}, email)
return ctx, true
}
return ctx, false
} | Base | 1 |
func (*CallApiEndpointRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{12}
} | Base | 1 |
func (x *StatusList_Status) Reset() {
*x = StatusList_Status{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[49]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | Base | 1 |
func PrintVerificationHeader(imgRef string, co *cosign.CheckOpts, bundleVerified bool) {
fmt.Fprintf(os.Stderr, "\nVerification for %s --\n", imgRef)
fmt.Fprintln(os.Stderr, "The following checks were performed on each of these signatures:")
if co.ClaimVerifier != nil {
if co.Annotations != nil {
fmt.Fprintln(os.Stderr, " - The specified annotations were verified.")
}
fmt.Fprintln(os.Stderr, " - The cosign claims were validated")
}
if bundleVerified {
fmt.Fprintln(os.Stderr, " - Existence of the claims in the transparency log was verified offline")
} else if co.RekorClient != nil {
fmt.Fprintln(os.Stderr, " - The claims were present in the transparency log")
fmt.Fprintln(os.Stderr, " - The signatures were integrated into the transparency log when the certificate was valid")
}
if co.SigVerifier != nil {
fmt.Fprintln(os.Stderr, " - The signatures were verified against the specified public key")
}
fmt.Fprintln(os.Stderr, " - Any certificates were verified against the Fulcio roots.")
} | Base | 1 |
func TestWrapHandler(t *testing.T) {
router := http.NewServeMux()
router.Handle("/", Handler(DocExpansion("none"), DomID("#swagger-ui")))
w1 := performRequest("GET", "/index.html", router)
assert.Equal(t, 200, w1.Code)
assert.Equal(t, w1.Header()["Content-Type"][0], "text/html; charset=utf-8")
w2 := performRequest("GET", "/doc.json", router)
assert.Equal(t, 500, w2.Code)
swag.Register(swag.Name, &mockedSwag{})
w2 = performRequest("GET", "/doc.json", router)
assert.Equal(t, 200, w2.Code)
assert.Equal(t, "application/json; charset=utf-8", w2.Header().Get("content-type"))
w3 := performRequest("GET", "/favicon-16x16.png", router)
assert.Equal(t, 200, w3.Code)
assert.Equal(t, w3.Header()["Content-Type"][0], "image/png")
w4 := performRequest("GET", "/swagger-ui.css", router)
assert.Equal(t, 200, w4.Code)
assert.Equal(t, w4.Header()["Content-Type"][0], "text/css; charset=utf-8")
w5 := performRequest("GET", "/swagger-ui-bundle.js", router)
assert.Equal(t, 200, w5.Code)
assert.Equal(t, w5.Header()["Content-Type"][0], "application/javascript")
w6 := performRequest("GET", "/notfound", router)
assert.Equal(t, 404, w6.Code)
w7 := performRequest("GET", "/", router)
assert.Equal(t, 301, w7.Code)
} | Class | 2 |
func (sg *SecureGet) Do(ctx context.Context) error {
ref, err := name.ParseReference(sg.ImageRef)
if err != nil {
return err
}
opts := []remote.Option{
remote.WithAuthFromKeychain(authn.DefaultKeychain),
remote.WithContext(ctx),
}
co := &cosign.CheckOpts{
ClaimVerifier: cosign.SimpleClaimVerifier,
RegistryClientOpts: []ociremote.Option{ociremote.WithRemoteOptions(opts...)},
}
if _, ok := ref.(name.Tag); ok {
if sg.KeyRef == "" && !options.EnableExperimental() {
return errors.New("public key must be specified when fetching by tag, you must fetch by digest or supply a public key")
}
}
// Overwrite "ref" with a digest to avoid a race where we verify the tag,
// and then access the file through the tag. This has a race where we
// might download content that isn't what we verified.
ref, err = ociremote.ResolveDigest(ref, co.RegistryClientOpts...)
if err != nil {
return err
}
if sg.KeyRef != "" {
pub, err := sigs.LoadPublicKey(ctx, sg.KeyRef)
if err != nil {
return err
}
co.SigVerifier = pub
}
if co.SigVerifier != nil || options.EnableExperimental() {
co.RootCerts = fulcio.GetRoots()
sp, bundleVerified, err := cosign.VerifyImageSignatures(ctx, ref, co)
if err != nil {
return err
}
verify.PrintVerificationHeader(sg.ImageRef, co, bundleVerified)
verify.PrintVerification(sg.ImageRef, sp, "text")
}
// TODO(mattmoor): Depending on what this is, use the higher-level stuff.
img, err := remote.Image(ref, opts...)
if err != nil {
return err
}
layers, err := img.Layers()
if err != nil {
return err
}
if len(layers) != 1 {
return errors.New("invalid artifact")
}
rc, err := layers[0].Compressed()
if err != nil {
return err
}
_, err = io.Copy(sg.Out, rc)
return err
} | Base | 1 |
Subsets and Splits