// This function is expected to be called as a goroutine.
// TODO: Track and log bytes copied, like TCP
325052
func (udp *udpProxySocket) proxyClient(cliAddr net.Addr, svrConn net.Conn, activeClients *clientCache, dnsClients *dnsClientCache, service ServicePortPortalName, timeout time.Duration, dnsSearch []string) {
	defer svrConn.Close()
	var buffer [4096]byte
	for {
		n, err := svrConn.Read(buffer[0:])
		if err != nil {
			if !logTimeout(err) {
				klog.Errorf("Read failed: %v", err)
			}
			break
		}

		drop := false
		if isDNSService(service.Port) {
			drop, n, err = processDNSResponsePacket(svrConn, dnsClients, cliAddr, buffer[:], n, dnsSearch)
			if err != nil {
				klog.Errorf("Process DNS response packet failed: %v", err)
			}
		}

		if !drop {
			err = svrConn.SetDeadline(time.Now().Add(timeout))
			if err != nil {
				klog.Errorf("SetDeadline failed: %v", err)
				break
			}
			n, err = udp.WriteTo(buffer[0:n], cliAddr)
			if err != nil {
				if !logTimeout(err) {
					klog.Errorf("WriteTo failed: %v", err)
				}
				break
			}
		}
	}
	activeClients.mu.Lock()
	delete(activeClients.clients, cliAddr.String())
	activeClients.mu.Unlock()
}
105922
func NewTrackedConnFromConn(conn *Conn, opTimer *prometheus.SummaryVec) (*TrackedConn, error) {
	return &TrackedConn{
		kt:      conn,
		opTimer: opTimer}, nil
}
621588
func (t *fileTrafficLog) Sent(message []byte) {
	t.mutex.Lock()
	defer t.mutex.Unlock()
	t.Messages = append(t.Messages, trafficLogRow{Sent: message})
}
203346
func (e Error) StackTraceString() string {
	buf := new(bytes.Buffer)
	for _, v := range e.Stack {
		fmt.Fprintf(buf, "%s: %s\n\t%s\n", v.File, v.Number, v.Method)
	}
	return string(buf.Bytes())
}
623196
func (frame *Frame) Func() *runtime.Func {
	if frame.ProgramCounter == 0 {
		return nil
	}
	return runtime.FuncForPC(frame.ProgramCounter)
}
1343530
func PrintStackTrace() {
	buf := make([]byte, 1<<16)
	runtime.Stack(buf, true)
	fmt.Printf("%s", buf)
}
790693
func ThisFunction() string {
	var pc [32]uintptr
	runtime.Callers(2, pc[:])
	return runtime.FuncForPC(pc[0]).Name()
}
354384
func (c *RPCClient) TraceDirectory() (string, error) {
	var out RecordedOut
	err := c.call("Recorded", RecordedIn{}, &out)
	return out.TraceDirectory, err
}
1344265
func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "index.html")
	})

	//When asked to log in, generate a unique state and store the entered values in a cookie to retreive on callback
	http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		s := &sessionInformation{
			ClientID:        r.FormValue("client_id"),
			Secret:          r.FormValue("secret"),
			RequestedScopes: r.FormValue("requested_scopes"),
		}
		fmt.Printf("Logging in to %s with secret %s and asking for scopes %s\n", s.ClientID, s.Secret, s.RequestedScopes)

		randombytes := make([]byte, 12) //Multiple of 3 to make sure no padding is added
		rand.Read(randombytes)
		state := base64.URLEncoding.EncodeToString(randombytes)

		serializedSessionInformation, _ := json.Marshal(s)
		sessionCookie := &http.Cookie{
			Name:   state,
			Value:  base64.URLEncoding.EncodeToString(serializedSessionInformation),
			MaxAge: 5 * 60, // 5 minutes
		}
		http.SetCookie(w, sessionCookie)

		u, _ := url.Parse("https://dev.itsyou.online:8443/v1/oauth/authorize")
		q := u.Query()
		q.Add("client_id", s.ClientID)
		q.Add("redirect_uri", "http://localhost:8080/callback")
		q.Add("scope", s.RequestedScopes)
		q.Add("state", state)
		q.Add("response_type", "code")
		u.RawQuery = q.Encode()
		http.Redirect(w, r, u.String(), http.StatusFound)
	})

	http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		code := r.FormValue("code")
		fmt.Println("Code: ", code)
		state := r.FormValue("state")

		sessionCookie, err := r.Cookie(state)
		if err != nil || sessionCookie == nil {
			fmt.Println("Failed to retrieve session cookie: ", err)
			fmt.Println("Cookie: ", sessionCookie)
			return
		}

		fmt.Println("Cookie value: ", sessionCookie.Value)

		decodedCookie, err := base64.URLEncoding.DecodeString(sessionCookie.Value)
		if err != nil {
			fmt.Println("Could not decode session cookie value: ", err)
		}
		s := &sessionInformation{}

		err = json.Unmarshal(decodedCookie, s)
		if err != nil {
			fmt.Println("Failed to convert session cookie: ", err)
			return
		}

		fmt.Println(s)

		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		hc := &http.Client{Transport: tr}
		req, err := http.NewRequest("POST", "https://dev.itsyou.online:8443/v1/oauth/access_token", nil)
		if err != nil {
			return
		}
		q := req.URL.Query()
		q.Add("client_id", s.ClientID)
		q.Add("client_secret", s.Secret)
		q.Add("code", code)
		q.Add("redirect_uri", "http://localhost:8080/callback")
		q.Add("state", state)
		req.URL.RawQuery = q.Encode()

		resp, err := hc.Do(req)
		if err != nil {
			fmt.Println("Error while getting the access token: ", err)
			return
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)

		fmt.Println("Response body: ", string(body))
		return

	})

	log.Fatal(http.ListenAndServe(":8080", nil))

}
908105
func (f *Fibre) Trace(p string, h HandlerFunc) {
	f.router.Add(TRACE, p, h)
}
804767
func (mr *MockSendAlgorithmMockRecorder) OnPacketAcked(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnPacketAcked", reflect.TypeOf((*MockSendAlgorithm)(nil).OnPacketAcked), arg0, arg1, arg2, arg3)
}
1333719
func (f *sendReceiveFolder) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState) {
	buf := protocol.BufferPool.Get(protocol.MinBlockSize)
	defer func() {
		protocol.BufferPool.Put(buf)
	}()

	for state := range in {
		dstFd, err := state.tempFile()
		if err != nil {
			// Nothing more to do for this failed file, since we couldn't create a temporary for it.
			out <- state.sharedPullerState
			continue
		}

		f.model.progressEmitter.Register(state.sharedPullerState)

		folderFilesystems := make(map[string]fs.Filesystem)
		var folders []string
		for folder, cfg := range f.model.cfg.Folders() {
			folderFilesystems[folder] = cfg.Filesystem()
			folders = append(folders, folder)
		}

		var file fs.File
		var weakHashFinder *weakhash.Finder

		blocksPercentChanged := 0
		if tot := len(state.file.Blocks); tot > 0 {
			blocksPercentChanged = (tot - state.have) * 100 / tot
		}

		if blocksPercentChanged >= f.WeakHashThresholdPct {
			hashesToFind := make([]uint32, 0, len(state.blocks))
			for _, block := range state.blocks {
				if block.WeakHash != 0 {
					hashesToFind = append(hashesToFind, block.WeakHash)
				}
			}

			if len(hashesToFind) > 0 {
				file, err = f.fs.Open(state.file.Name)
				if err == nil {
					weakHashFinder, err = weakhash.NewFinder(f.ctx, file, int(state.file.BlockSize()), hashesToFind)
					if err != nil {
						l.Debugln("weak hasher", err)
					}
				}
			} else {
				l.Debugf("not weak hashing %s. file did not contain any weak hashes", state.file.Name)
			}
		} else {
			l.Debugf("not weak hashing %s. not enough changed %.02f < %d", state.file.Name, blocksPercentChanged, f.WeakHashThresholdPct)
		}

	blocks:
		for _, block := range state.blocks {
			select {
			case <-f.ctx.Done():
				state.fail(errors.Wrap(f.ctx.Err(), "folder stopped"))
				break blocks
			default:
			}

			if !f.DisableSparseFiles && state.reused == 0 && block.IsEmpty() {
				// The block is a block of all zeroes, and we are not reusing
				// a temp file, so there is no need to do anything with it.
				// If we were reusing a temp file and had this block to copy,
				// it would be because the block in the temp file was *not* a
				// block of all zeroes, so then we should not skip it.

				// Pretend we copied it.
				state.copiedFromOrigin()
				state.copyDone(block)
				continue
			}

			buf = protocol.BufferPool.Upgrade(buf, int(block.Size))

			found, err := weakHashFinder.Iterate(block.WeakHash, buf, func(offset int64) bool {
				if verifyBuffer(buf, block) != nil {
					return true
				}

				_, err = dstFd.WriteAt(buf, block.Offset)
				if err != nil {
					state.fail(errors.Wrap(err, "dst write"))

				}
				if offset == block.Offset {
					state.copiedFromOrigin()
				} else {
					state.copiedFromOriginShifted()
				}

				return false
			})
			if err != nil {
				l.Debugln("weak hasher iter", err)
			}

			if !found {
				found = f.model.finder.Iterate(folders, block.Hash, func(folder, path string, index int32) bool {
					fs := folderFilesystems[folder]
					fd, err := fs.Open(path)
					if err != nil {
						return false
					}

					_, err = fd.ReadAt(buf, int64(state.file.BlockSize())*int64(index))
					fd.Close()
					if err != nil {
						return false
					}

					if err := verifyBuffer(buf, block); err != nil {
						l.Debugln("Finder failed to verify buffer", err)
						return false
					}

					_, err = dstFd.WriteAt(buf, block.Offset)
					if err != nil {
						state.fail(errors.Wrap(err, "dst write"))
					}
					if path == state.file.Name {
						state.copiedFromOrigin()
					}
					return true
				})
			}

			if state.failed() != nil {
				break
			}

			if !found {
				state.pullStarted()
				ps := pullBlockState{
					sharedPullerState: state.sharedPullerState,
					block:             block,
				}
				pullChan <- ps
			} else {
				state.copyDone(block)
			}
		}
		if file != nil {
			// os.File used to return invalid argument if nil.
			// fs.File panics as it's an interface.
			file.Close()
		}

		out <- state.sharedPullerState
	}
}
925277
func (c *Tracing) RequestMemoryDump() (string, bool, error) {
	resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Tracing.requestMemoryDump"})
	if err != nil {
		return "", false, err
	}

	var chromeData struct {
		Result struct {
			DumpGuid string
			Success  bool
		}
	}

	if resp == nil {
		return "", false, &gcdmessage.ChromeEmptyResponseErr{}
	}

	// test if error first
	cerr := &gcdmessage.ChromeErrorResponse{}
	json.Unmarshal(resp.Data, cerr)
	if cerr != nil && cerr.Error != nil {
		return "", false, &gcdmessage.ChromeRequestErr{Resp: cerr}
	}

	if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
		return "", false, err
	}

	return chromeData.Result.DumpGuid, chromeData.Result.Success, nil
}
721844
func (g *G) Go() Location {
	pc := g.GoPC
	if fn := g.variable.bi.PCToFunc(pc); fn != nil {
		// Backup to CALL instruction.
		// Mimics runtime/traceback.go:677.
		if g.GoPC > fn.Entry {
			pc--
		}
	}
	f, l, fn := g.variable.bi.PCToLine(pc)
	return Location{PC: g.GoPC, File: f, Line: l, Fn: fn}
}
1338556
func go_callback(id C.int, data *C.uchar, len C.int, queue_id C.int) {
	// TODO: check cast of id
	payload := &RawPacket{
		ID:   uint32(id),
		Data: C.GoBytes(unsafe.Pointer(data), len),
	}

	dispatch(uint16(queue_id), payload)
}
1222816
func (c *Cubic) CongestionWindowAfterAck(
	ackedBytes protocol.ByteCount,
	currentCongestionWindow protocol.ByteCount,
	delayMin time.Duration,
	eventTime time.Time,
) protocol.ByteCount {
	c.ackedBytesCount += ackedBytes

	if c.epoch.IsZero() {
		// First ACK after a loss event.
		c.epoch = eventTime            // Start of epoch.
		c.ackedBytesCount = ackedBytes // Reset count.
		// Reset estimated_tcp_congestion_window_ to be in sync with cubic.
		c.estimatedTCPcongestionWindow = currentCongestionWindow
		if c.lastMaxCongestionWindow <= currentCongestionWindow {
			c.timeToOriginPoint = 0
			c.originPointCongestionWindow = currentCongestionWindow
		} else {
			c.timeToOriginPoint = uint32(math.Cbrt(float64(cubeFactor * (c.lastMaxCongestionWindow - currentCongestionWindow))))
			c.originPointCongestionWindow = c.lastMaxCongestionWindow
		}
	}

	// Change the time unit from microseconds to 2^10 fractions per second. Take
	// the round trip time in account. This is done to allow us to use shift as a
	// divide operator.
	elapsedTime := int64(eventTime.Add(delayMin).Sub(c.epoch)/time.Microsecond) << 10 / (1000 * 1000)

	// Right-shifts of negative, signed numbers have implementation-dependent
	// behavior, so force the offset to be positive, as is done in the kernel.
	offset := int64(c.timeToOriginPoint) - elapsedTime
	if offset < 0 {
		offset = -offset
	}

	deltaCongestionWindow := protocol.ByteCount(cubeCongestionWindowScale*offset*offset*offset) * protocol.DefaultTCPMSS >> cubeScale
	var targetCongestionWindow protocol.ByteCount
	if elapsedTime > int64(c.timeToOriginPoint) {
		targetCongestionWindow = c.originPointCongestionWindow + deltaCongestionWindow
	} else {
		targetCongestionWindow = c.originPointCongestionWindow - deltaCongestionWindow
	}
	// Limit the CWND increase to half the acked bytes.
	targetCongestionWindow = utils.MinByteCount(targetCongestionWindow, currentCongestionWindow+c.ackedBytesCount/2)

	// Increase the window by approximately Alpha * 1 MSS of bytes every
	// time we ack an estimated tcp window of bytes.  For small
	// congestion windows (less than 25), the formula below will
	// increase slightly slower than linearly per estimated tcp window
	// of bytes.
	c.estimatedTCPcongestionWindow += protocol.ByteCount(float32(c.ackedBytesCount) * c.alpha() * float32(protocol.DefaultTCPMSS) / float32(c.estimatedTCPcongestionWindow))
	c.ackedBytesCount = 0

	// We have a new cubic congestion window.
	c.lastTargetCongestionWindow = targetCongestionWindow

	// Compute target congestion_window based on cubic target and estimated TCP
	// congestion_window, use highest (fastest).
	if targetCongestionWindow < c.estimatedTCPcongestionWindow {
		targetCongestionWindow = c.estimatedTCPcongestionWindow
	}
	return targetCongestionWindow
}
992389
func (s *Server) HandleTracePacket(packet []byte) {
	samples := &ssf.Samples{}
	defer metrics.Report(s.TraceClient, samples)

	// Unlike metrics, protobuf shouldn't have an issue with 0-length packets
	if len(packet) == 0 {
		s.Statsd.Count("ssf.error_total", 1, []string{"ssf_format:packet", "packet_type:unknown", "reason:zerolength"}, 1.0)
		log.Warn("received zero-length trace packet")
		return
	}

	s.Statsd.Histogram("ssf.packet_size", float64(len(packet)), nil, .1)

	span, err := protocol.ParseSSF(packet)
	if err != nil {
		reason := "reason:" + err.Error()
		s.Statsd.Count("ssf.error_total", 1, []string{"ssf_format:packet", "packet_type:ssf_metric", reason}, 1.0)
		log.WithError(err).Warn("ParseSSF")
		return
	}
	// we want to keep track of this, because it's a client problem, but still
	// handle the span normally
	if span.Id == 0 {
		reason := "reason:" + "empty_id"
		s.Statsd.Count("ssf.error_total", 1, []string{"ssf_format:packet", "packet_type:ssf_metric", reason}, 1.0)
		log.WithError(err).Warn("ParseSSF")
	}

	s.handleSSF(span, "packet")
}