func host_to_rpc(host *graph.Host, states []state.HostState, metrics map[string][]metric.MetricValue) *rpc.Node {
	node := &rpc.Node{
		Id:         proto.Int32(int32(host.Id)),
		Name:       proto.String(host.Name),
		Address:    proto.String(host.Address),
		Model:      proto.String(host.Model),
		MacAddress: proto.String(host.MACAddress),
		Comment:    proto.String(host.Comment),
		Serial:     proto.String(host.Serial),
		Ip4:        proto.Uint32(ipv4_to_uint32(host.IP)),
		Ip6:        []byte(host.IP6.To16()),
		DbId:       proto.Int32(int32(host.DBImportSwitchId)),
		IcingaName: proto.String(host.IcingaName),
		Type:       rpc.Node_NodeType(host.Type).Enum(),
	}
	if len(states) > 0 {
		node.States = make([]*rpc.NodeState, len(states))
		for index, s := range states {
			n_state := &rpc.NodeState{
				Rtt:                 proto.Float32(s.RTT),
				Loss:                proto.Float32(s.Loss),
				State:               rpc.NodeState_State(s.State).Enum(),
				HardState:           rpc.NodeState_State(s.HardState).Enum(),
				DescriptiveState:    rpc.NodeState_DescState(s.EffectiveState).Enum(),
				IsHardState:         proto.Bool(s.IsHardState),
				IsFlapping:          proto.Bool(s.IsFlapping),
				IsReachable:         proto.Bool(s.IsReachable),
				IsExecuting:         proto.Bool(s.IsExecuting),
				Time:                proto.Uint64(uint64(s.Time.Unix())),
				Source:              proto.String(s.Source),
				Output:              proto.String(s.Output),
				NumServices:         proto.Int32(s.NumServices),
				NumServicesOk:       proto.Int32(s.NumServicesOk),
				NumServicesCritical: proto.Int32(s.NumServicesCritical),
				NumServicesWarning:  proto.Int32(s.NumServicesWarning),
				NumServicesPending:  proto.Int32(s.NumServicesPending),
				NumServicesUnknown:  proto.Int32(s.NumServicesUnknown),
				Notes:               proto.String(s.Notes),
				HasBeenChecked:      proto.Bool(s.HasBeenChecked),
				IsDuplicate:         proto.Bool(s.IsDuplicate),
			}
			node.States[index] = n_state
		}
	}
	node.LastMetricValues = make(map[string]*rpc.MetricValCollection)
	for key := range metrics {
		values, _ := metrics[key]
		if len(values) == 0 {
			continue
		}
		collection := &rpc.MetricValCollection{}
		collection.Name = proto.String(key)
		collection.Values = make([]*rpc.MetricVal, len(values))
		for index, value := range values {
			collection.Values[index], _ = metric_value_to_rpc(value)
		}
		node.LastMetricValues[key] = collection
	}
	return node
}
Example #2
0
// Float32P parses the given string representation of a floating point number,
// and returns a pointer to a float32 whose value is same as the parsed number.
func Float32P(val string) (*float32, error) {
	f, err := Float32(val)
	if err != nil {
		return nil, err
	}
	return proto.Float32(f), nil
}
// normalizeAppApk normalizes values in the "apk" section of App.
func normalizeAppApk(p *bspb.BatteryStats_App_Apk, totalTimeHour float64) *bspb.BatteryStats_App_Apk {
	norm := &bspb.BatteryStats_App_Apk{}

	// there's only one wakeups value per apk
	norm.Wakeups = proto.Float32(float32(roundToTwoDecimal(float64(p.GetWakeups()) / totalTimeHour)))
	norm.Service = normalizeRepeatedMessage(p.GetService(), totalTimeHour).Interface().([]*bspb.BatteryStats_App_Apk_Service)
	return norm
}
Example #4
0
func newTestMessage() *pb.MyMessage {
	msg := &pb.MyMessage{
		Count: proto.Int32(42),
		Name:  proto.String("Dave"),
		Quote: proto.String(`"I didn't want to go."`),
		Pet:   []string{"bunny", "kitty", "horsey"},
		Inner: &pb.InnerMessage{
			Host:      proto.String("footrest.syd"),
			Port:      proto.Int32(7001),
			Connected: proto.Bool(true),
		},
		Others: []*pb.OtherMessage{
			{
				Key:   proto.Int64(0xdeadbeef),
				Value: []byte{1, 65, 7, 12},
			},
			{
				Weight: proto.Float32(6.022),
				Inner: &pb.InnerMessage{
					Host: proto.String("lesha.mtv"),
					Port: proto.Int32(8002),
				},
			},
		},
		Bikeshed: pb.MyMessage_BLUE.Enum(),
		Somegroup: &pb.MyMessage_SomeGroup{
			GroupField: proto.Int32(8),
		},
		// One normally wouldn't do this.
		// This is an undeclared tag 13, as a varint (wire type 0) with value 4.
		XXX_unrecognized: []byte{13<<3 | 0, 4},
	}
	ext := &pb.Ext{
		Data: proto.String("Big gobs for big rats"),
	}
	if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil {
		panic(err)
	}
	greetings := []string{"adg", "easy", "cow"}
	if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil {
		panic(err)
	}

	// Add an unknown extension. We marshal a pb.Ext, and fake the ID.
	b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")})
	if err != nil {
		panic(err)
	}
	b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...)
	proto.SetRawExtension(msg, 201, b)

	// Extensions can be plain fields, too, so let's test that.
	b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19)
	proto.SetRawExtension(msg, 202, b)

	return msg
}
// subtractSystemBatteryLevel sets start level to the current level of the first proto.
func subtractSystemBatteryLevel(p1, p2 *bspb.BatteryStats_System_BatteryLevel) *bspb.BatteryStats_System_BatteryLevel {
	if p1 == nil && p2 == nil {
		return nil
	}
	if p2 == nil {
		return proto.Clone(p1).(*bspb.BatteryStats_System_BatteryLevel)
	}
	if p1 == nil {
		return proto.Clone(p2).(*bspb.BatteryStats_System_BatteryLevel)

	}
	d := &bspb.BatteryStats_System_BatteryLevel{}

	// CurrentLevel is set as the diff between the current level of the 2 protos.
	d.CurrentLevel = proto.Float32(p1.GetCurrentLevel() - p2.GetCurrentLevel())
	// Startlevel is set to the level of the first proto which is our main proto against which we want to diff the other one
	d.StartLevel = proto.Float32(p1.GetCurrentLevel())
	return d
}
Example #6
0
func InitTermFreqRow(tfr *TermFreqRow, field uint16, term []byte, docID []byte, docNum uint64, freq uint64, norm float32, termVectors []*TermVector) *TermFreqRow {
	tfr.field = field
	tfr.term = term
	tfr.docID = docID
	tfr.docNum = docNum
	tfr.value.Freq = proto.Uint64(freq)
	tfr.value.Norm = proto.Float32(norm)
	tfr.value.Vectors = termVectors
	return tfr
}
Example #7
0
func createDropoutLayer(name string, bottom string, top string, ratio float32) *caffe.LayerParameter {
	return &caffe.LayerParameter{
		Name:   proto.String(name),
		Type:   proto.String("Dropout"),
		Bottom: []string{bottom},
		Top:    []string{top},
		DropoutParam: &caffe.DropoutParameter{
			DropoutRatio: proto.Float32(ratio),
		},
		Include: []*caffe.NetStateRule{
			&caffe.NetStateRule{
				Phase: caffe.Phase_TRAIN.Enum(),
			},
		},
	}
}
Example #8
0
func convertToProtoSuiteResult(suiteResult *suiteResult) *gauge_messages.ProtoSuiteResult {
	protoSuiteResult := &gauge_messages.ProtoSuiteResult{
		PreHookFailure:   suiteResult.preSuite,
		PostHookFailure:  suiteResult.postSuite,
		Failed:           proto.Bool(suiteResult.isFailed),
		SpecsFailedCount: proto.Int32(int32(suiteResult.specsFailedCount)),
		ExecutionTime:    proto.Int64(suiteResult.executionTime),
		SpecResults:      convertToProtoSpecResult(suiteResult.specResults),
		SuccessRate:      proto.Float32(getSuccessRate(len(suiteResult.specResults), suiteResult.specsFailedCount)),
		Environment:      proto.String(suiteResult.environment),
		Tags:             proto.String(suiteResult.tags),
		ProjectName:      proto.String(suiteResult.projectName),
		Timestamp:        proto.String(suiteResult.timestamp),
	}
	return protoSuiteResult
}
// subtractAppApk computes differences of "apk" in App. p2 will be subtracted from p1.
func subtractAppApk(p1, p2 *bspb.BatteryStats_App_Apk) *bspb.BatteryStats_App_Apk {
	d := &bspb.BatteryStats_App_Apk{}
	apkChanged := false
	// there's only one wakeups value per apk, compare wakeups separately
	if diffWakeups := p1.GetWakeups() - p2.GetWakeups(); diffWakeups != 0 {
		apkChanged = true
		d.Wakeups = proto.Float32(diffWakeups)
	}
	if diff := subtractRepeatedMessage(p1.GetService(), p2.GetService()); !diff.IsNil() {
		apkChanged = true
		d.Service = diff.Interface().([]*bspb.BatteryStats_App_Apk_Service)
	}
	if apkChanged {
		return d
	}
	return nil
}
func metric_value_to_rpc(m metric.MetricValue) (rpc_val *rpc.MetricVal, err error) {
	rpc_val = &rpc.MetricVal{
		Time: proto.Uint64(uint64(m.Time.Unix())),
		Kind: rpc.MetricVal_Kind(m.Kind + 1).Enum(),
		Name: proto.String(m.Name),
		Type: proto.String("host"),
	}
	err = nil
	defer func() {
		if r := recover(); r != nil {
			switch x := r.(type) {
			case string:
				err = errors.New(x)
			case error:
				err = x
			default:
				err = errors.New("Unknown panic")
			}
			log.Printf("Recover metric_value_to_rpc from error: %v\n", err)
		}
	}()
	switch m.Kind {
	case metric.METRIC_GAUGE:
		rpc_val.GaugeValue = proto.Float32(float32(m.Value.(float64)))
	case metric.METRIC_COUNTER:
		rpc_val.CounterValue = proto.Uint64(m.Value.(uint64))
	case metric.METRIC_DERIVE:
		rpc_val.DeriveValue = proto.Int64(m.Value.(int64))
	default:
		buffer := &bytes.Buffer{}
		err := binary.Write(buffer, binary.LittleEndian, m.Value)
		if err != nil {
			log.Printf("Cannot serialize data: %s\n", err)
		} else {
			rpc_val.OtherValue = buffer.Bytes()
		}
	}
	return
}
Example #11
0
func populateMessage(pb *test_pb.TestAllTypes) {
	pb.OptionalInt32 = proto.Int32(101)
	pb.OptionalInt64 = proto.Int64(102)
	pb.OptionalUint32 = proto.Uint32(103)
	pb.OptionalUint64 = proto.Uint64(104)
	pb.OptionalSint32 = proto.Int32(105)
	pb.OptionalSint64 = proto.Int64(106)
	pb.OptionalFixed32 = proto.Uint32(107)
	pb.OptionalFixed64 = proto.Uint64(108)
	pb.OptionalSfixed32 = proto.Int32(109)
	pb.OptionalSfixed64 = proto.Int64(110)
	pb.OptionalFloat = proto.Float32(111.5)
	pb.OptionalDouble = proto.Float64(112.5)
	pb.OptionalBool = proto.Bool(true)
	pb.OptionalString = proto.String("test")
	pb.OptionalBytes = []byte("abcd")

	group := &test_pb.TestAllTypes_OptionalGroup{}
	group.A = proto.Int32(111)
	pb.Optionalgroup = group

	nestedMessage := &test_pb.TestAllTypes_NestedMessage{}
	nestedMessage.B = proto.Int32(112)
	pb.OptionalNestedMessage = nestedMessage

	pb.OptionalNestedEnum = test_pb.TestAllTypes_FOO.Enum()

	pb.RepeatedInt32 = append(pb.RepeatedInt32, 201)
	pb.RepeatedInt32 = append(pb.RepeatedInt32, 202)

	pb.RepeatedString = append(pb.RepeatedString, "foo")
	pb.RepeatedString = append(pb.RepeatedString, "bar")

	pb.RepeatedNestedEnum = append(pb.RepeatedNestedEnum,
		test_pb.TestAllTypes_FOO)
	pb.RepeatedNestedEnum = append(pb.RepeatedNestedEnum,
		test_pb.TestAllTypes_BAR)
}
Example #12
0
// Fills serializer in dt_field
func (pst *PropertySerializerTable) FillSerializer(field *dt_field) {
	// Handle special decoders that need the complete field data here
	switch field.Name {
	case "m_flSimulationTime":
		field.Serializer = &PropertySerializer{decodeSimTime, nil, false, 0, nil, "unkown"}
		return
	case "m_flAnimTime":
		field.Serializer = &PropertySerializer{decodeSimTime, nil, false, 0, nil, "unkown"}
		return
	}

	// Handle special fields in old replays where the low and high values of a
	// quantized float were invalid.
	if field.build < 955 {
		switch field.Name {
		case "m_flMana", "m_flMaxMana":
			field.LowValue = nil
			field.HighValue = proto.Float32(8192.0)
		}

	}

	field.Serializer = pst.GetPropertySerializerByName(field.Type)
}
Example #13
0
var (
	marshaler = Marshaler{}

	marshalerAllOptions = Marshaler{
		Indent: "  ",
	}

	simpleObject = &pb.Simple{
		OInt32:  proto.Int32(-32),
		OInt64:  proto.Int64(-6400000000),
		OUint32: proto.Uint32(32),
		OUint64: proto.Uint64(6400000000),
		OSint32: proto.Int32(-13),
		OSint64: proto.Int64(-2600000000),
		OFloat:  proto.Float32(3.14),
		ODouble: proto.Float64(6.02214179e23),
		OBool:   proto.Bool(true),
		OString: proto.String("hello \"there\""),
		OBytes:  []byte("beep boop"),
	}

	simpleObjectJSON = `{` +
		`"o_bool":true,` +
		`"o_int32":-32,` +
		`"o_int64":"-6400000000",` +
		`"o_uint32":32,` +
		`"o_uint64":"6400000000",` +
		`"o_sint32":-13,` +
		`"o_sint64":"-2600000000",` +
		`"o_float":3.14,` +
Example #14
0
// NewRandomRowFilter is TODO
func NewRandomRowFilter(chance float32) *RandomRowFilter {
	return &RandomRowFilter{
		Chance: proto.Float32(chance),
	}
}
Example #15
0
		json string
	}{
		{data: "", json: `""`},
		{data: proto.String(""), json: `""`},
		{data: "foo", json: `"foo"`},
		{data: proto.String("foo"), json: `"foo"`},
		{data: int32(-1), json: "-1"},
		{data: proto.Int32(-1), json: "-1"},
		{data: int64(-1), json: "-1"},
		{data: proto.Int64(-1), json: "-1"},
		{data: uint32(123), json: "123"},
		{data: proto.Uint32(123), json: "123"},
		{data: uint64(123), json: "123"},
		{data: proto.Uint64(123), json: "123"},
		{data: float32(-1.5), json: "-1.5"},
		{data: proto.Float32(-1.5), json: "-1.5"},
		{data: float64(-1.5), json: "-1.5"},
		{data: proto.Float64(-1.5), json: "-1.5"},
		{data: true, json: "true"},
		{data: proto.Bool(true), json: "true"},
		{data: (*string)(nil), json: "null"},
		{data: new(empty.Empty), json: "{}"},
		{data: examplepb.NumericEnum_ONE, json: "1"},
		{
			data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))),
			json: "1",
		},
	}
	builtinKnownErrors = []struct {
		data interface{}
		json string
Example #16
0
func TestPopulateParameters(t *testing.T) {
	for _, spec := range []struct {
		values url.Values
		filter *internal.DoubleArray
		want   proto.Message
	}{
		{
			values: url.Values{
				"float_value":    {"1.5"},
				"double_value":   {"2.5"},
				"int64_value":    {"-1"},
				"int32_value":    {"-2"},
				"uint64_value":   {"3"},
				"uint32_value":   {"4"},
				"bool_value":     {"true"},
				"string_value":   {"str"},
				"repeated_value": {"a", "b", "c"},
			},
			filter: internal.NewDoubleArray(nil),
			want: &proto3Message{
				FloatValue:    1.5,
				DoubleValue:   2.5,
				Int64Value:    -1,
				Int32Value:    -2,
				Uint64Value:   3,
				Uint32Value:   4,
				BoolValue:     true,
				StringValue:   "str",
				RepeatedValue: []string{"a", "b", "c"},
			},
		},
		{
			values: url.Values{
				"float_value":    {"1.5"},
				"double_value":   {"2.5"},
				"int64_value":    {"-1"},
				"int32_value":    {"-2"},
				"uint64_value":   {"3"},
				"uint32_value":   {"4"},
				"bool_value":     {"true"},
				"string_value":   {"str"},
				"repeated_value": {"a", "b", "c"},
			},
			filter: internal.NewDoubleArray(nil),
			want: &proto2Message{
				FloatValue:    proto.Float32(1.5),
				DoubleValue:   proto.Float64(2.5),
				Int64Value:    proto.Int64(-1),
				Int32Value:    proto.Int32(-2),
				Uint64Value:   proto.Uint64(3),
				Uint32Value:   proto.Uint32(4),
				BoolValue:     proto.Bool(true),
				StringValue:   proto.String("str"),
				RepeatedValue: []string{"a", "b", "c"},
			},
		},
		{
			values: url.Values{
				"nested.nested.nested.repeated_value": {"a", "b", "c"},
				"nested.nested.nested.string_value":   {"s"},
				"nested.nested.string_value":          {"t"},
				"nested.string_value":                 {"u"},
				"nested_non_null.string_value":        {"v"},
			},
			filter: internal.NewDoubleArray(nil),
			want: &proto3Message{
				Nested: &proto2Message{
					Nested: &proto3Message{
						Nested: &proto2Message{
							RepeatedValue: []string{"a", "b", "c"},
							StringValue:   proto.String("s"),
						},
						StringValue: "t",
					},
					StringValue: proto.String("u"),
				},
				NestedNonNull: proto2Message{
					StringValue: proto.String("v"),
				},
			},
		},
		{
			values: url.Values{
				"uint64_value": {"1", "2", "3", "4", "5"},
			},
			filter: internal.NewDoubleArray(nil),
			want: &proto3Message{
				Uint64Value: 1,
			},
		},
	} {
		msg := proto.Clone(spec.want)
		msg.Reset()
		err := runtime.PopulateQueryParameters(msg, spec.values, spec.filter)
		if err != nil {
			t.Errorf("runtime.PoplateQueryParameters(msg, %v, %v) failed with %v; want success", spec.values, spec.filter, err)
			continue
		}
		if got, want := msg, spec.want; !proto.Equal(got, want) {
			t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v = %v; want %v", spec.values, spec.filter, got, want)
		}
	}
}
Example #17
0
File: bnet.go Project: laiqu/stove
func (session *session) handleRequest(packet []byte) int {
	if len(packet) < 2 {
		return -1
	}
	headerSize := binary.BigEndian.Uint16(packet)
	if 2+int(headerSize) > len(packet) {
		fmt.Printf("CO DO KURWY %d\n", int(headerSize))
		return -2
	}
	headerData := packet[2 : 2+int(headerSize)]
	fmt.Printf("%x\n", headerData)

	header := &hsproto.BnetProtocol_Header{}
	err := proto.Unmarshal(headerData, header)
	check(err)
	if header.GetStatus() != 0 {
		fmt.Println("header status != 0! :(")
	}

	packetEnd := 2 + int(headerSize) + int(header.GetSize())
	if packetEnd > len(packet) {
		fmt.Printf("SZTO? %d %d\n", header.GetSize(), packetEnd)
		return -3
	}
	bodyData := packet[2+headerSize : packetEnd]

	if header.GetServiceId() == 0 && header.GetMethodId() == 1 {
		body := &hsproto.BnetProtocolConnection_ConnectRequest{}
		err = proto.Unmarshal(bodyData, body)
		check(err)

		// register services
		connService := ConnectionService{Service{"bnet.protocol.connection.ConnectionService", 0}}
		authServerService := AuthServerService{Service{"bnet.protocol.authentication.AuthenticationServer", 1}}
		authClientService := AuthClientService{Service{"bnet.protocol.authentication.AuthenticationClient", 255}}
		fmt.Printf("connService=%d, authServerService=%d, authClientService=%d\n",
			connService.GetHashedName(),
			authServerService.GetHashedName(),
			authClientService.GetHashedName(),
		)

		bindRequest := body.GetBindRequest()
		// iterate
		for _, importedHash := range bindRequest.GetImportedServiceHash() {
			fmt.Printf("Client imports service %d probably: %s\n", importedHash, HashToName(importedHash))
		}

		for _, export := range bindRequest.GetExportedService() {
			fmt.Printf("Client exports service id=%d, hash=%d probably: %s\n", export.GetId(), export.GetHash(), HashToName(export.GetHash()))
		}

		timestamp := uint64(time.Now().UnixNano() / 1000)
		epoch := uint32(time.Now().Unix())

		resp := &hsproto.BnetProtocolConnection_ConnectResponse{
			ServerId: &hsproto.BnetProtocol_ProcessId{
				Label: proto.Uint32(3868510373),
				Epoch: proto.Uint32(epoch),
			},
			ClientId: &hsproto.BnetProtocol_ProcessId{
				Label: proto.Uint32(1255760),
				Epoch: proto.Uint32(epoch),
			},
			BindResult: proto.Uint32(0),
			BindResponse: &hsproto.BnetProtocolConnection_BindResponse{
				ImportedServiceId: []uint32{
					1,
					2,
					3,
					4,
					5,
					6,
					7,
					8,
					9,
					10,
					11,
					12,
				},
			},
			ServerTime: proto.Uint64(timestamp),
		}

		data, err := proto.Marshal(resp)
		check(err)
		header := &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			MethodId:  proto.Uint32(1),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(uint32(len(data))),
		}

		session.writePacket(header, data)
	} else if header.GetServiceId() == 1 && header.GetMethodId() == 1 {
		fmt.Println("Auth Logon")
		body := &hsproto.BnetProtocolAuthentication_LogonRequest{}
		err = proto.Unmarshal(bodyData, body)
		check(err)

		header := &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(0),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, make([]byte, 0))

		resp := &hsproto.BnetProtocolAuthentication_LogonQueueUpdateRequest{
			Position:          proto.Uint32(0),
			EstimatedTime:     proto.Uint64(0),
			EtaDeviationInSec: proto.Uint64(0),
		}
		data, err := proto.Marshal(resp)
		check(err)
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(1),
			MethodId:  proto.Uint32(12),
			Token:     proto.Uint32(0),
			Size:      proto.Uint32(uint32(len(data))),
		}
		session.writePacket(header, data)

		respUpd := &hsproto.BnetProtocolAuthentication_LogonUpdateRequest{
			ErrorCode: proto.Uint32(0),
		}
		data, err = proto.Marshal(respUpd)
		check(err)
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(1),
			MethodId:  proto.Uint32(10),
			Token:     proto.Uint32(2),
			Size:      proto.Uint32(uint32(len(data))),
		}
		session.writePacket(header, data)

		respResult := &hsproto.BnetProtocolAuthentication_LogonResult{
			ErrorCode: proto.Uint32(0),
			Account: &hsproto.BnetProtocol_EntityId{
				High: proto.Uint64(1),
				Low:  proto.Uint64(0),
			},
			GameAccount: []*hsproto.BnetProtocol_EntityId{
				&hsproto.BnetProtocol_EntityId{
					High: proto.Uint64(2),
					Low:  proto.Uint64(0),
				},
			},
			ConnectedRegion: proto.Uint32(0),
		}
		data, err = proto.Marshal(respResult)
		check(err)
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(1),
			MethodId:  proto.Uint32(5),
			Token:     proto.Uint32(3),
			Size:      proto.Uint32(uint32(len(data))),
		}
		session.writePacket(header, data)
	} else if header.GetServiceId() == 1 && header.GetMethodId() == 4 {
		fmt.Println("Auth SelectGameAccount")
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(0),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, make([]byte, 0))
	} else if header.GetServiceId() == 5 && header.GetMethodId() == 1 {
		fmt.Println("Presence Subscribe")
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(0),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, make([]byte, 0))
	} else if header.GetServiceId() == 5 && header.GetMethodId() == 3 {
		fmt.Println("Presence Update")
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(0),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, make([]byte, 0))
	} else if header.GetServiceId() == 11 && header.GetMethodId() == 30 {
		fmt.Println("Account GetAccountState")
		count := "EU"
		resp := &hsproto.BnetProtocolAccount_GetAccountStateResponse{
			State: &hsproto.BnetProtocolAccount_AccountState{
				AccountLevelInfo: &hsproto.BnetProtocolAccount_AccountLevelInfo{
					Licenses: []*hsproto.BnetProtocolAccount_AccountLicense{
						&hsproto.BnetProtocolAccount_AccountLicense{
							Id: proto.Uint32(0),
						},
					},
					DefaultCurrency: proto.Uint32(0),
					Country:         &count,
					PreferredRegion: proto.Uint32(0),
				},
			},
		}
		data, err := proto.Marshal(resp)
		check(err)
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(uint32(len(data))),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, data)
	} else if header.GetServiceId() == 11 && header.GetMethodId() == 34 {
		fmt.Println("Account GetGameSessionInfo")
		resp := &hsproto.BnetProtocolAccount_GetGameSessionInfoResponse{
			SessionInfo: &hsproto.BnetProtocolAccount_GameSessionInfo{
				StartTime: proto.Uint32(uint32(time.Now().Unix())),
			},
		}
		data, err := proto.Marshal(resp)
		check(err)
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(uint32(len(data))),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, data)
	} else if header.GetServiceId() == 9 && header.GetMethodId() == 1 {
		fmt.Println("Friends SubscribeToFriends")
		resp := &hsproto.BnetProtocolFriends_SubscribeToFriendsResponse{
			MaxFriends:             proto.Uint32(100),
			MaxReceivedInvitations: proto.Uint32(42),
			MaxSentInvitations:     proto.Uint32(7),
		}
		data, err := proto.Marshal(resp)
		check(err)
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(uint32(len(data))),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, data)
	} else if header.GetServiceId() == 12 && header.GetMethodId() == 1 {
		fmt.Println("Resources GetContentHandle")
		contentRequest := &hsproto.BnetProtocolResources_ContentHandleRequest{}
		err := proto.Unmarshal(bodyData, contentRequest)
		fmt.Printf("%d %d\n", contentRequest.GetProgramId(), contentRequest.GetStreamId())
		resp := &hsproto.BnetProtocol_ContentHandle{
			Region: proto.Uint32(0),
			Usage:  proto.Uint32(0),
			Hash:   make([]byte, 0),
		}
		data, err := proto.Marshal(resp)
		check(err)
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(uint32(len(data))),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, data)
	} else if header.GetServiceId() == 8 && header.GetMethodId() == 1 {
		fmt.Println("ChannelInvitation Subscribe")
		resp := &hsproto.BnetProtocolChannelInvitation_SubscribeResponse{}
		data, err := proto.Marshal(resp)
		check(err)
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(uint32(len(data))),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, data)
	} else if header.GetServiceId() == 2 && header.GetMethodId() == 1 {
		fmt.Println("GameUtilities ClientRequest")
		clientRequest := &hsproto.BnetProtocolGameUtilities_ClientRequest{}
		proto.Unmarshal(bodyData, clientRequest)
		if len(clientRequest.GetAttribute()) != 2 {
			fmt.Println("Too many attributes in pegasus client request?")
		}
		packetType := int64(-1)
		var pegasusData []byte
		for _, att := range clientRequest.GetAttribute() {
			//fmt.Println(att.GetName())
			if att.GetName() == "p" {
				//fmt.Printf("%x\n", att.GetValue().GetBlobValue())
				blob := att.GetValue().GetBlobValue()
				if len(blob) < 2 {
					fmt.Println("blob is too short")
				} else {
					packetType = int64(blob[0]) + int64(blob[1])<<8
					pegasusData = blob[2:]
				}
			}
		}
		name := "it shouldn't matter"
		resp := &hsproto.BnetProtocolGameUtilities_ClientResponse{}
		if packetType == 314 {
			fmt.Println("pegasus 314 - subscribe")
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(315),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: []byte{},
						},
					},
				},
			}
		} else if packetType == 303 {
			fmt.Println("pegasus 303 - get assets")
			assetResp := &hsproto.PegasusUtil_AssetsVersionResponse{
				Version: proto.Int32(7553),
			}
			assData, err := proto.Marshal(assetResp)
			check(err)
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(304),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: assData,
						},
					},
				},
			}
		} else if packetType == 267 {
			fmt.Println("pegasus 267 - check account licenses")
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(325),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: []byte{},
						},
					},
				},
			}
		} else if packetType == 276 {
			fmt.Println("pegasus 276 - check game licenses")
			licResp := &hsproto.PegasusUtil_CheckLicensesResponse{
				AccountLevel: proto.Bool(true),
				Success:      proto.Bool(true),
			}
			licData, err := proto.Marshal(licResp)
			check(err)
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(277),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: licData,
						},
					},
				},
			}
		} else if packetType == 205 {
			fmt.Println("pegasus 205 - update login")
			updResp := &hsproto.PegasusUtil_UpdateLoginComplete{}
			updData, err := proto.Marshal(updResp)
			check(err)
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(307),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: updData,
						},
					},
				},
			}
		} else if packetType == 201 {
			fmt.Println("pegasus 201 - get account info")
			accountInfoReq := &hsproto.PegasusUtil_GetAccountInfo{}
			err := proto.Unmarshal(pegasusData, accountInfoReq)
			check(err)
			requestType := accountInfoReq.GetRequest()
			fmt.Println(requestType)
			attBlob := []byte{}
			respType := int64(505)
			if requestType == hsproto.PegasusUtil_GetAccountInfo_CAMPAIGN_INFO {
				profileProgress := &hsproto.PegasusUtil_ProfileProgress{
					Progress:  proto.Int64(6),
					BestForge: proto.Int32(10),
					LastForge: &hsproto.PegasusShared_Date{
						Year:  proto.Int32(2015),
						Month: proto.Int32(3),
						Day:   proto.Int32(31),
						Hours: proto.Int32(17),
						Min:   proto.Int32(3),
						Sec:   proto.Int32(54),
					},
				}
				attBlob, err = proto.Marshal(profileProgress)
				check(err)
				respType = 233
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_BOOSTERS {
				boosters := &hsproto.PegasusUtil_BoosterList{}
				attBlob, err = proto.Marshal(boosters)
				check(err)
				respType = 224
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_FEATURES {
				features := &hsproto.PegasusUtil_GuardianVars{
					ShowUserUI: proto.Int32(1),
				}
				attBlob, err = proto.Marshal(features)
				check(err)
				respType = 264
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_MEDAL_INFO {
				medalInfo := &hsproto.PegasusUtil_MedalInfo{
					SeasonWins: proto.Int32(0),
					Stars:      proto.Int32(20),
					Streak:     proto.Int32(0),
					StarLevel:  proto.Int32(9),
					LevelStart: proto.Int32(20),
					LevelEnd:   proto.Int32(3),
					CanLose:    proto.Bool(true),
				}
				attBlob, err = proto.Marshal(medalInfo)
				check(err)
				respType = 232
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_NOTICES {
				notices := &hsproto.PegasusUtil_ProfileNotices{}
				attBlob, err = proto.Marshal(notices)
				check(err)
				respType = 212
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_DECK_LIST {
				deckList := &hsproto.PegasusUtil_DeckList{}
				attBlob, err = proto.Marshal(deckList)
				check(err)
				respType = 202
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_COLLECTION {
				collection := &hsproto.PegasusUtil_Collection{}
				attBlob, err = proto.Marshal(collection)
				check(err)
				respType = 207
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_DECK_LIMIT {
				deckLimit := &hsproto.PegasusUtil_ProfileDeckLimit{
					DeckLimit: proto.Int32(9),
				}
				attBlob, err = proto.Marshal(deckLimit)
				check(err)
				respType = 231
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_CARD_VALUES {
				cardValues := &hsproto.PegasusUtil_CardValues{
					CardNerfIndex: proto.Int32(5),
				}
				attBlob, err = proto.Marshal(cardValues)
				check(err)
				respType = 260
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_ARCANE_DUST_BALANCE {
				arcaneDust := &hsproto.PegasusUtil_ArcaneDustBalance{
					Balance: proto.Int64(1337),
				}
				attBlob, err = proto.Marshal(arcaneDust)
				check(err)
				respType = 262
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_NOT_SO_MASSIVE_LOGIN {
				notMassive := &hsproto.PegasusUtil_NotSoMassiveLoginReply{}
				attBlob, err = proto.Marshal(notMassive)
				check(err)
				respType = int64(hsproto.PegasusUtil_NotSoMassiveLoginReply_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_REWARD_PROGRESS {
				rewardProgress := &hsproto.PegasusUtil_RewardProgress{
					SeasonEnd: &hsproto.PegasusShared_Date{
						Year:  proto.Int32(2015),
						Month: proto.Int32(4),
						Day:   proto.Int32(30),
						Hours: proto.Int32(22),
						Min:   proto.Int32(0),
						Sec:   proto.Int32(0),
					},
					WinsPerGold:   proto.Int32(3),
					GoldPerReward: proto.Int32(10),
					MaxGoldPerDay: proto.Int32(100),
					SeasonNumber:  proto.Int32(18),
					XpSoloLimit:   proto.Int32(60),
					MaxHeroLevel:  proto.Int32(60),
					NextQuestCancel: &hsproto.PegasusShared_Date{
						Year:  proto.Int32(2015),
						Month: proto.Int32(4),
						Day:   proto.Int32(1),
						Hours: proto.Int32(0),
						Min:   proto.Int32(0),
						Sec:   proto.Int32(0),
					},
					EventTimingMod: proto.Float32(-0.0833333283662796),
				}

				attBlob, err = proto.Marshal(rewardProgress)
				check(err)
				respType = int64(hsproto.PegasusUtil_RewardProgress_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_BOOSTER_TALLY {
				boosterTally := &hsproto.PegasusUtil_BoosterTallyList{}
				attBlob, err = proto.Marshal(boosterTally)
				check(err)
				respType = int64(hsproto.PegasusUtil_BoosterTallyList_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_PLAYER_RECORD {
				playerRecords := &hsproto.PegasusUtil_PlayerRecords{}
				attBlob, err = proto.Marshal(playerRecords)
				check(err)
				respType = int64(hsproto.PegasusUtil_PlayerRecords_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_GOLD_BALANCE {
				goldBalance := &hsproto.PegasusUtil_GoldBalance{
					CappedBalance: proto.Int64(1000),
					BonusBalance:  proto.Int64(0),
					Cap:           proto.Int64(999999),
					CapWarning:    proto.Int64(999999),
				}
				attBlob, err = proto.Marshal(goldBalance)
				check(err)
				respType = int64(hsproto.PegasusUtil_GoldBalance_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_HERO_XP {
				heroXP := &hsproto.PegasusUtil_HeroXP{
					XpInfos: make([]*hsproto.PegasusUtil_HeroXPInfo, 10),
				}
				for i := int32(2); i < 12; i++ {
					heroXP.XpInfos[i-2] = &hsproto.PegasusUtil_HeroXPInfo{
						ClassId: proto.Int32(i),
						Level:   proto.Int32(60),
						CurrXp:  proto.Int64(1480),
						MaxXp:   proto.Int64(1480),
					}
				}
				attBlob, err = proto.Marshal(heroXP)
				check(err)
				respType = int64(hsproto.PegasusUtil_HeroXP_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_CARD_BACKS {
				cardBacks := &hsproto.PegasusUtil_CardBacks{
					DefaultCardBack: proto.Int32(13),
					CardBacks:       make([]int32, 19),
				}
				for i := int32(1); i < 20; i++ {
					cardBacks.CardBacks[i-1] = i
				}
				attBlob, err = proto.Marshal(cardBacks)
				check(err)
				respType = int64(hsproto.PegasusUtil_CardBacks_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_FAVORITE_HEROES {
				playerRecords := &hsproto.PegasusUtil_FavoriteHeroesResponse{}
				attBlob, err = proto.Marshal(playerRecords)
				check(err)
				respType = int64(hsproto.PegasusUtil_FavoriteHeroesResponse_PacketID_value["ID"])
			} else if requestType == hsproto.PegasusUtil_GetAccountInfo_TAVERN_BRAWL_INFO {
				tavernInfo := &hsproto.PegasusUtil_TavernBrawlInfo{}
				attBlob, err = proto.Marshal(tavernInfo)
				check(err)
				respType = int64(hsproto.PegasusUtil_TavernBrawlInfo_PacketID_value["ID"])
			}
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(respType),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: attBlob,
						},
					},
				},
			}
		} else if packetType == 305 {
			fmt.Println("pegasus 305 - adventure progress")
			adventureProgress := &hsproto.PegasusUtil_AdventureProgressResponse{}
			adventureData, err := proto.Marshal(adventureProgress)
			check(err)
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(int64(hsproto.PegasusUtil_AdventureProgressResponse_PacketID_value["ID"])),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: adventureData,
						},
					},
				},
			}
		} else if packetType == 240 {
			fmt.Println("pegasus 240 - get options")
			clientOptions := &hsproto.PegasusUtil_ClientOptions{}
			clientData, err := proto.Marshal(clientOptions)
			check(err)
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(int64(hsproto.PegasusUtil_ClientOptions_PacketID_value["ID"])),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: clientData,
						},
					},
				},
			}
		} else if packetType == 237 {
			fmt.Println("pegasus 237 - get battle pay status")
			battlePayConfig := &hsproto.PegasusUtil_BattlePayConfigResponse{
				Currency:             proto.Int32(2),
				Unavailable:          proto.Bool(true),
				SecsBeforeAutoCancel: proto.Int32(600),
				GoldCostArena:        proto.Int64(150),
			}
			battlePayData, err := proto.Marshal(battlePayConfig)
			check(err)
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(int64(hsproto.PegasusUtil_BattlePayConfigResponse_PacketID_value["ID"])),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: battlePayData,
						},
					},
				},
			}
		} else if packetType == 253 {
			fmt.Println("pegasus 253 - get achieves")
			achieves := &hsproto.PegasusUtil_Achieves{}
			achievesData, err := proto.Marshal(achieves)
			check(err)
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(int64(hsproto.PegasusUtil_Achieves_PacketID_value["ID"])),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: achievesData,
						},
					},
				},
			}
		} else if int32(packetType) == hsproto.PegasusUtil_ValidateAchieve_PacketID_value["ID"] {
			fmt.Println("pegasus get achieves")
			validateAchieveReq := &hsproto.PegasusUtil_ValidateAchieve{}
			err := proto.Unmarshal(pegasusData, validateAchieveReq)
			achieves := &hsproto.PegasusUtil_ValidateAchieveResponse{
				Achieve: proto.Int32(validateAchieveReq.GetAchieve()),
			}
			achievesData, err := proto.Marshal(achieves)
			check(err)
			resp = &hsproto.BnetProtocolGameUtilities_ClientResponse{
				Attribute: []*hsproto.BnetProtocolAttribute_Attribute{
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							IntValue: proto.Int64(int64(hsproto.PegasusUtil_ValidateAchieveResponse_PacketID_value["ID"])),
						},
					},
					&hsproto.BnetProtocolAttribute_Attribute{
						Name: &name,
						Value: &hsproto.BnetProtocolAttribute_Variant{
							BlobValue: achievesData,
						},
					},
				},
			}
		} else {
			fmt.Printf("UNSOLVED packet type %d\n", packetType)
		}
		data, err := proto.Marshal(resp)
		check(err)
		header = &hsproto.BnetProtocol_Header{
			ServiceId: proto.Uint32(254),
			Token:     proto.Uint32(header.GetToken()),
			Size:      proto.Uint32(uint32(len(data))),
			Status:    proto.Uint32(0),
		}
		session.writePacket(header, data)
	} else if header.GetServiceId() == 0 && header.GetMethodId() == 5 {
		fmt.Println("Keep alive!")
	} else {
		fmt.Printf("unsupported: %d, %d, bodylen: %d\n %x\nheader: %x\n", header.GetServiceId(), header.GetMethodId(), len(bodyData), string(bodyData[:]), string(headerData[:]))
	}
	return packetEnd
}
Example #18
0
// StateToProtocolBuffer converts a State type to a proto.State
func StateToProtocolBuffer(state *State) (*proto.State, error) {
	if state.Host == "" {
		state.Host, _ = os.Hostname()
	}
	if state.Time == 0 {
		state.Time = time.Now().Unix()
	}

	var e proto.State
	t := reflect.ValueOf(&e).Elem()
	s := reflect.ValueOf(state).Elem()
	typeOfEvent := s.Type()

	for i := 0; i < s.NumField(); i++ {
		f := s.Field(i)
		value := reflect.ValueOf(f.Interface())
		if reflect.Zero(f.Type()) != value && f.Interface() != nil {
			name := typeOfEvent.Field(i).Name
			switch name {
			case "State", "Service", "Host", "Description":
				tmp := reflect.ValueOf(pb.String(value.String()))
				t.FieldByName(name).Set(tmp)
			case "Once":
				tmp := reflect.ValueOf(pb.Bool(bool(value.Bool())))
				t.FieldByName(name).Set(tmp)
			case "Ttl":
				tmp := reflect.ValueOf(pb.Float32(float32(value.Float())))
				t.FieldByName(name).Set(tmp)
			case "Time":
				tmp := reflect.ValueOf(pb.Int64(value.Int()))
				t.FieldByName(name).Set(tmp)
			case "Tags":
				tmp := reflect.ValueOf(value.Interface().([]string))
				t.FieldByName(name).Set(tmp)
			case "Metric":
				switch reflect.TypeOf(f.Interface()).Kind() {
				case reflect.Int:
					tmp := reflect.ValueOf(pb.Int64(int64(value.Int())))
					t.FieldByName("MetricSint64").Set(tmp)
				case reflect.Float32:
					tmp := reflect.ValueOf(pb.Float32(float32(value.Float())))
					t.FieldByName("MetricF").Set(tmp)
				case reflect.Float64:
					tmp := reflect.ValueOf(pb.Float64(value.Float()))
					t.FieldByName("MetricD").Set(tmp)
				default:
					return nil, fmt.Errorf("Metric of invalid type (type %v)",
						reflect.TypeOf(f.Interface()).Kind())
				}
			case "Attributes":
				var attrs []*proto.Attribute
				for k, v := range value.Interface().(map[string]string) {
					k_, v_ := k, v
					attrs = append(attrs, &proto.Attribute{
						Key:   &k_,
						Value: &v_,
					})
				}
				t.FieldByName(name).Set(reflect.ValueOf(attrs))
			}
		}
	}
	return &e, nil
}
Example #19
0
func eventToPbEvent(event *Event) (*proto.Event, error) {
	var e proto.Event

	if event.Host == "" {
		event.Host, _ = os.Hostname()
	}
	t := reflect.ValueOf(&e).Elem()
	s := reflect.ValueOf(event).Elem()
	typeOfEvent := s.Type()
	for i := 0; i < s.NumField(); i++ {
		f := s.Field(i)
		value := reflect.ValueOf(f.Interface())
		if !isZero(f) {
			name := typeOfEvent.Field(i).Name
			switch name {
			case "State", "Service", "Host", "Description":
				tmp := reflect.ValueOf(pb.String(value.String()))
				t.FieldByName(name).Set(tmp)
			case "Ttl":
				tmp := reflect.ValueOf(pb.Float32(float32(value.Float())))
				t.FieldByName(name).Set(tmp)
			case "Time":
				tmp := reflect.ValueOf(pb.Int64(value.Int()))
				t.FieldByName(name).Set(tmp)
			case "Tags":
				tmp := reflect.ValueOf(value.Interface().([]string))
				t.FieldByName(name).Set(tmp)
			case "Metric":
				switch reflect.TypeOf(f.Interface()).Kind() {
				case reflect.Int:
					tmp := reflect.ValueOf(pb.Int64(int64(value.Int())))
					t.FieldByName("MetricSint64").Set(tmp)
				case reflect.Int64:
					tmp := reflect.ValueOf(pb.Int64(int64(value.Int())))
					t.FieldByName("MetricSint64").Set(tmp)
				case reflect.Float32:
					tmp := reflect.ValueOf(pb.Float32(float32(value.Float())))
					t.FieldByName("MetricF").Set(tmp)
				case reflect.Float64:
					tmp := reflect.ValueOf(pb.Float64(value.Float()))
					t.FieldByName("MetricD").Set(tmp)
				default:
					return nil, fmt.Errorf("Metric of invalid type (type %v)",
						reflect.TypeOf(f.Interface()).Kind())
				}
			case "Attributes":
				var attrs []*proto.Attribute
				for k, v := range value.Interface().(map[string]string) {
					// Copy k,v so we can take
					// pointers to the new
					// temporaries
					k_, v_ := k, v
					attrs = append(attrs, &proto.Attribute{
						Key:   &k_,
						Value: &v_,
					})
				}
				t.FieldByName(name).Set(reflect.ValueOf(attrs))
			}
		}
	}

	return &e, nil
}
Example #20
0
func main() {
	vars := []proto.Message{
		&pb.M0{F: proto.Int32(0)},
		&pb.M0{F: proto.Int32(-1000000), XXX_unrecognized: []byte{0, 1, 2}},
		&pb.M1{F: proto.Int64(0)},
		&pb.M1{F: proto.Int64(100)},
		&pb.M1{F: proto.Int64(123123123123123123)},
		&pb.M1{F: proto.Int64(-100)},
		&pb.M1{F: proto.Int64(-123123123123123123)},
		&pb.M2{},
		&pb.M2{F: proto.Uint32(123123)},
		&pb.M3{},
		&pb.M3{F: proto.Uint64(123123123123123123)},
		&pb.M4{F: proto.Int32(123123)},
		&pb.M5{F: proto.Int64(123123)},
		&pb.M5{F: proto.Int64(-123123)},
		&pb.M6{XXX_unrecognized: []byte{0, 1, 2}},
		&pb.M6{F: proto.Uint32(123123), XXX_unrecognized: []byte{0, 1, 2}},
		&pb.M7{F: proto.Uint64(123123123123)},
		&pb.M8{F: proto.Int32(-123123)},
		&pb.M9{F: proto.Int64(-123123123123)},
		&pb.M10{F: proto.Float64(123123.123123)},
		&pb.M11{F: proto.Float32(123123.123123)},
		&pb.M12{F: proto.Bool(true)},
		&pb.M13{},
		&pb.M13{F: proto.String("")},
		&pb.M13{F: proto.String("foo")},
		&pb.M13{F: proto.String("&pb.M6{F: proto.Uint32(123123), XXX_unrecognized: []byte{0,1,2}},")},
		&pb.M13{F: proto.String("\x00\x01\x02")},
		&pb.M14{},
		&pb.M14{F: []byte{0, 1, 2}},
		&pb.M14{F: []byte("&pb.M6{F: proto.Uint32(123123), XXX_unrecognized: []byte{0,1,2}},")},
		&pb.M15{F0: proto.Int32(123)},
		&pb.M15{F0: proto.Int32(123), F1: proto.String("foo"), F2: []byte{1, 2, 3}, F4: proto.Bool(false)},
		&pb.M16{},
		&pb.M16{F: pb.Corpus_UNIVERSAL.Enum()},
		&pb.M16{F: pb.Corpus_PRODUCTS.Enum()},
		&pb.M17{F: &pb.M15{F0: proto.Int32(123)}},
		&pb.M17{F: &pb.M15{F0: proto.Int32(123), F1: proto.String("foo"), F2: []byte{1, 2, 3}, F4: proto.Bool(false)}},
		func() proto.Message {
			v := &pb.M18{F0: proto.String("foo")}
			proto.SetExtension(v, pb.E_F1, 42)
			return v
		}(),
		&pb.M19{},
		&pb.M19{F: []int32{0, -123, 500, 123123123}},
		&pb.M20{F: []string{"", "foo", "\x00\x01\x02"}},
		&pb.M21{F: []*pb.M15{&pb.M15{F0: proto.Int32(123)}, &pb.M15{F0: proto.Int32(123), F1: proto.String("foo"), F2: []byte{1, 2, 3}, F4: proto.Bool(false)}}},
		&pb.M22{F: []*pb.M2{&pb.M2{}}},
		&pb.M22{F: []*pb.M2{&pb.M2{}, &pb.M2{F: proto.Uint32(123123)}}},
		&pb.M23{},
		&pb.M23{F: map[int32]string{42: "", 11: "foo", 123123123: "\x00\x01\x02"}},
		&pb.M24{F: map[string]*pb.M2{"": &pb.M2{}, "foo": &pb.M2{}, "\x00\x01\x02": &pb.M2{F: proto.Uint32(123123)}}},
		&pb.M25{},
		&pb.M25{F0: proto.String("")},
		&pb.M25{F0: proto.String("foo")},
		&pb.M25{F1: &pb.M2{}},
		&pb.M25{F1: &pb.M2{F: proto.Uint32(123123)}},
		&pb.M25{F2: pb.Corpus_UNIVERSAL.Enum()},
	}
	for i, v := range vars {
		if false {
			data, err := proto.Marshal(v)
			if err != nil {
				panic(err)
			}
			f, err := os.Create(fmt.Sprintf("/tmp/proto/%v", i))
			if err != nil {
				panic(err)
			}
			f.Write(data)
			f.Close()
		} else {
			f, err := os.Create(fmt.Sprintf("/tmp/proto/%v", i))
			if err != nil {
				panic(err)
			}
			fmt.Printf("%v: %+v\n", i, v)
			err = proto.MarshalText(f, v)
			if err != nil {
				panic(err)
			}
			f.Close()
		}
	}
}
		data          interface{}
		json          string
		skipUnmarshal bool
	}{
		{data: int32(1), json: "1"},
		{data: proto.Int32(1), json: "1"},
		{data: int64(1), json: "1"},
		{data: proto.Int64(1), json: "1"},
		{data: uint32(1), json: "1"},
		{data: proto.Uint32(1), json: "1"},
		{data: uint64(1), json: "1"},
		{data: proto.Uint64(1), json: "1"},
		{data: "abc", json: `"abc"`},
		{data: proto.String("abc"), json: `"abc"`},
		{data: float32(1.5), json: "1.5"},
		{data: proto.Float32(1.5), json: "1.5"},
		{data: float64(1.5), json: "1.5"},
		{data: proto.Float64(1.5), json: "1.5"},
		{data: true, json: "true"},
		{data: false, json: "false"},
		{data: (*string)(nil), json: "null"},
		{
			data: examplepb.NumericEnum_ONE,
			json: `"ONE"`,
			// TODO(yugui) support unmarshaling of symbolic enum
			skipUnmarshal: true,
		},
		{
			data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))),
			json: `"ONE"`,
			// TODO(yugui) support unmarshaling of symbolic enum
Example #22
0
func OnGetAccountInfo(s *Session, body []byte) *Packet {
	req := util.GetAccountInfo{}
	err := proto.Unmarshal(body, &req)
	if err != nil {
		panic(err)
	}
	log.Printf("req = %s", req.String())
	switch req.Request.String() {
	case "CAMPAIGN_INFO":
		res := util.ProfileProgress{}
		res.Progress = proto.Int64(6)  // ILLIDAN_COMPLETE
		res.BestForge = proto.Int32(0) // Arena wins
		return EncodePacket(util.ProfileProgress_ID, &res)
	case "BOOSTERS":
		res := util.BoosterList{}
		classicPacks := s.GetBoosterInfo(1)
		gvgPacks := s.GetBoosterInfo(9)
		tgtPacks := s.GetBoosterInfo(10)
		if *classicPacks.Count > 0 {
			res.List = append(res.List, classicPacks)
		}
		if *gvgPacks.Count > 0 {
			res.List = append(res.List, gvgPacks)
		}
		if *tgtPacks.Count > 0 {
			res.List = append(res.List, tgtPacks)
		}
		return EncodePacket(util.BoosterList_ID, &res)
	case "FEATURES":
		res := util.GuardianVars{}
		res.ShowUserUI = proto.Int32(1)
		return EncodePacket(util.GuardianVars_ID, &res)
	case "MEDAL_INFO":
		res := util.MedalInfo{}
		res.SeasonWins = proto.Int32(0)
		res.Stars = proto.Int32(2)
		res.Streak = proto.Int32(0)
		res.StarLevel = proto.Int32(1)
		res.LevelStart = proto.Int32(1)
		res.LevelEnd = proto.Int32(3)
		res.CanLose = proto.Bool(false)
		return EncodePacket(util.MedalInfo_ID, &res)
	case "MEDAL_HISTORY":
		res := util.MedalHistory{}
		for i := int32(1); i <= 3; i++ {
			info := &util.MedalHistoryInfo{}
			info.When = PegasusDate(time.Date(2015, 8, 1, 7, 0, 0, 0, time.UTC))
			info.Season = proto.Int32(i)
			info.Stars = proto.Int32(0)
			info.StarLevel = proto.Int32(0)
			info.LevelStart = proto.Int32(0)
			info.LevelEnd = proto.Int32(0)
			info.LegendRank = proto.Int32(1)
			res.Medals = append(res.Medals, info)
		}
		return EncodePacket(util.MedalHistory_ID, &res)
	case "NOTICES":
		res := util.ProfileNotices{}
		return EncodePacket(util.ProfileNotices_ID, &res)
	case "DECK_LIST":
		res := util.DeckList{}
		basicDecks := []Deck{}
		deckType := shared.DeckType_PRECON_DECK
		db.Where("deck_type = ?", deckType).Find(&basicDecks)
		for _, deck := range basicDecks {
			info := MakeDeckInfo(&deck)
			res.Decks = append(res.Decks, info)
		}
		decks := []Deck{}
		deckType = shared.DeckType_NORMAL_DECK
		db.Where("deck_type = ? and account_id = ?", deckType, s.Account.ID).Find(&decks)
		for _, deck := range decks {
			info := MakeDeckInfo(&deck)
			res.Decks = append(res.Decks, info)
		}
		return EncodePacket(util.DeckList_ID, &res)
	case "COLLECTION":
		res := util.Collection{}
		collectionCards := []CollectionCard{}
		db.Where("account_id = ?", s.Account.ID).Find(&collectionCards)
		for _, card := range collectionCards {
			stack1 := &shared.CardStack{}
			stack1.LatestInsertDate = PegasusDate(time.Now().UTC())
			stack1.NumSeen = proto.Int32(2)
			stack1.Count = proto.Int32(card.Num)
			carddef := &shared.CardDef{}
			carddef.Asset = proto.Int32(card.CardID)
			carddef.Premium = proto.Int32(card.Premium)
			stack1.CardDef = carddef
			res.Stacks = append(res.Stacks, stack1)
		}
		return EncodePacket(util.Collection_ID, &res)
	case "DECK_LIMIT":
		res := util.ProfileDeckLimit{}
		res.DeckLimit = proto.Int32(9)
		return EncodePacket(util.ProfileDeckLimit_ID, &res)
	case "CARD_VALUES":
		res := util.CardValues{}
		dbfCards := []DbfCard{}
		db.Where("is_collectible = ? AND buy_price is not ?", true, 0).Find(&dbfCards)
		for _, cards := range dbfCards {
			card := &util.CardValue{}
			cardPremium := &util.CardValue{}
			card.Card = MakeCardDef(cards.ID, 0)
			card.Buy = proto.Int32(cards.BuyPrice)
			card.Sell = proto.Int32(cards.SellPrice)
			card.Nerfed = proto.Bool(false)
			cardPremium.Card = MakeCardDef(cards.ID, 1)
			cardPremium.Buy = proto.Int32(cards.GoldBuyPrice)
			cardPremium.Sell = proto.Int32(cards.GoldSellPrice)
			cardPremium.Nerfed = proto.Bool(false)
			res.Cards = append(res.Cards, card)
			res.Cards = append(res.Cards, cardPremium)
		}
		res.CardNerfIndex = proto.Int32(0)
		return EncodePacket(util.CardValues_ID, &res)
	case "ARCANE_DUST_BALANCE":
		res := util.ArcaneDustBalance{}
		account := Account{}
		db.Where("id = ?", s.Account.ID).First(&account)
		res.Balance = proto.Int64(account.Dust)
		return EncodePacket(util.ArcaneDustBalance_ID, &res)
	case "GOLD_BALANCE":
		res := util.GoldBalance{}
		account := Account{}
		db.Where("id = ?", s.Account.ID).First(&account)
		res.Cap = proto.Int64(999999)
		res.CapWarning = proto.Int64(2000)
		res.CappedBalance = proto.Int64(account.Gold)
		res.BonusBalance = proto.Int64(0)
		return EncodePacket(util.GoldBalance_ID, &res)
	case "HERO_XP":
		res := util.HeroXP{}
		for i := 2; i <= 10; i++ {
			info := &util.HeroXPInfo{}
			level := 2*i + 5
			maxXp := 60 + level*10
			info.ClassId = proto.Int32(int32(i))
			info.Level = proto.Int32(int32(level))
			info.CurrXp = proto.Int64(int64(maxXp / 2))
			info.MaxXp = proto.Int64(int64(maxXp))
			res.XpInfos = append(res.XpInfos, info)
		}
		return EncodePacket(util.HeroXP_ID, &res)
	case "NOT_SO_MASSIVE_LOGIN":
		res := util.NotSoMassiveLoginReply{}
		return EncodePacket(util.NotSoMassiveLoginReply_ID, &res)
	case "REWARD_PROGRESS":
		res := util.RewardProgress{}
		nextMonth := time.Date(2015, 8, 1, 7, 0, 0, 0, time.UTC)
		res.SeasonEnd = PegasusDate(nextMonth)
		res.WinsPerGold = proto.Int32(3)
		res.GoldPerReward = proto.Int32(10)
		res.MaxGoldPerDay = proto.Int32(100)
		res.SeasonNumber = proto.Int32(21)
		res.XpSoloLimit = proto.Int32(60)
		res.MaxHeroLevel = proto.Int32(60)
		res.NextQuestCancel = PegasusDate(time.Now().UTC())
		res.EventTimingMod = proto.Float32(0.291667)
		return EncodePacket(util.RewardProgress_ID, &res)
	case "PVP_QUEUE":
		res := util.PlayQueue{}
		queue := shared.PlayQueueInfo{}
		gametype := shared.BnetGameType_BGT_NORMAL
		queue.GameType = &gametype
		res.Queue = &queue
		return EncodePacket(util.PlayQueue_ID, &res)

	case "PLAYER_RECORD":
		res := util.PlayerRecords{}
		return EncodePacket(util.PlayerRecords_ID, &res)
	case "CARD_BACKS":
		res := util.CardBacks{}
		dbfCardBacks := []DbfCardBack{}
		res.DefaultCardBack = proto.Int32(0)
		db.Find(&dbfCardBacks)
		for _, cardBack := range dbfCardBacks {
			res.CardBacks = append(res.CardBacks, cardBack.ID)
		}
		return EncodePacket(util.CardBacks_ID, &res)
	case "FAVORITE_HEROES":
		res := util.FavoriteHeroesResponse{}
		favoriteHeros := []FavoriteHero{}
		db.Where("account_id = ?", s.Account.ID).Find(&favoriteHeros)
		for _, hero := range favoriteHeros {
			card := DbfCard{}
			db.Where("id = ?", hero.CardID).First(&card)
			carddef := &shared.CardDef{}
			carddef.Asset = proto.Int32(hero.CardID)
			carddef.Premium = proto.Int32(hero.Premium)
			fav := &shared.FavoriteHero{}
			fav.ClassId = proto.Int32(hero.ClassID)
			fav.Hero = carddef
			res.FavoriteHeroes = append(res.FavoriteHeroes, fav)
		}
		return EncodePacket(util.FavoriteHeroesResponse_ID, &res)
	case "ACCOUNT_LICENSES":
		res := util.AccountLicensesInfoResponse{}
		return EncodePacket(util.AccountLicensesInfoResponse_ID, &res)
	case "BOOSTER_TALLY":
		res := util.BoosterTallyList{}
		return EncodePacket(util.BoosterTallyList_ID, &res)
	default:
		panic(nyi)
	}
}
Example #23
0
// User stats message. Shown in the Mumble client when a
// user right clicks a user and selects 'User Information'.
func (server *Server) handleUserStatsMessage(client *Client, msg *Message) {
	stats := &mumbleproto.UserStats{}
	err := proto.Unmarshal(msg.buf, stats)
	if err != nil {
		client.Panic(err)
		return
	}

	if stats.Session == nil {
		return
	}

	target, exists := server.clients[*stats.Session]
	if !exists {
		return
	}

	extended := false
	// If a client is requesting a UserStats from itself, serve it the whole deal.
	if client == target {
		extended = true
	}
	// Otherwise, only send extended UserStats for people with +register permissions
	// on the root channel.
	rootChan := server.RootChannel()
	if acl.HasPermission(&rootChan.ACL, client, acl.RegisterPermission) {
		extended = true
	}

	// If the client wasn't granted extended permissions, only allow it to query
	// users in channels it can enter.
	if !extended && !acl.HasPermission(&target.Channel.ACL, client, acl.EnterPermission) {
		client.sendPermissionDenied(client, target.Channel, acl.EnterPermission)
		return
	}

	details := extended
	local := extended || target.Channel == client.Channel

	if stats.StatsOnly != nil && *stats.StatsOnly == true {
		details = false
	}

	stats.Reset()
	stats.Session = proto.Uint32(target.Session())

	if details {
		if tlsconn := target.conn.(*tls.Conn); tlsconn != nil {
			state := tlsconn.ConnectionState()
			for i := len(state.PeerCertificates) - 1; i >= 0; i-- {
				stats.Certificates = append(stats.Certificates, state.PeerCertificates[i].Raw)
			}
			stats.StrongCertificate = proto.Bool(target.IsVerified())
		}
	}

	if local {
		fromClient := &mumbleproto.UserStats_Stats{}
		fromClient.Good = proto.Uint32(target.crypt.Good)
		fromClient.Late = proto.Uint32(target.crypt.Late)
		fromClient.Lost = proto.Uint32(target.crypt.Lost)
		fromClient.Resync = proto.Uint32(target.crypt.Resync)
		stats.FromClient = fromClient

		fromServer := &mumbleproto.UserStats_Stats{}
		fromServer.Good = proto.Uint32(target.crypt.RemoteGood)
		fromServer.Late = proto.Uint32(target.crypt.RemoteLate)
		fromServer.Lost = proto.Uint32(target.crypt.RemoteLost)
		fromServer.Resync = proto.Uint32(target.crypt.RemoteResync)
		stats.FromServer = fromServer
	}

	stats.UdpPackets = proto.Uint32(target.UdpPackets)
	stats.TcpPackets = proto.Uint32(target.TcpPackets)
	stats.UdpPingAvg = proto.Float32(target.UdpPingAvg)
	stats.UdpPingVar = proto.Float32(target.UdpPingVar)
	stats.TcpPingAvg = proto.Float32(target.TcpPingAvg)
	stats.TcpPingVar = proto.Float32(target.TcpPingVar)

	if details {
		version := &mumbleproto.Version{}
		version.Version = proto.Uint32(target.Version)
		if len(target.ClientName) > 0 {
			version.Release = proto.String(target.ClientName)
		}
		if len(target.OSName) > 0 {
			version.Os = proto.String(target.OSName)
			if len(target.OSVersion) > 0 {
				version.OsVersion = proto.String(target.OSVersion)
			}
		}
		stats.Version = version
		stats.CeltVersions = target.codecs
		stats.Opus = proto.Bool(target.opus)
		stats.Address = target.tcpaddr.IP
	}

	// fixme(mkrautz): we don't do bandwidth tracking yet

	if err := client.sendMessage(stats); err != nil {
		client.Panic(err)
		return
	}
}