<commit_before>// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/hid/hid_connection_linux.h"

#include <errno.h>
#include <linux/hidraw.h>
#include <sys/ioctl.h>

#include <string>

#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_pump_libevent.h"
#include "base/posix/eintr_wrapper.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/thread_restrictions.h"
#include "device/hid/hid_service.h"

// These are already defined in newer versions of linux/hidraw.h.
#ifndef HIDIOCSFEATURE
#define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE | _IOC_READ, 'H', 0x06, len)
#endif
#ifndef HIDIOCGFEATURE
#define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE | _IOC_READ, 'H', 0x07, len)
#endif

namespace device {

class HidConnectionLinux::Helper : public base::MessagePumpLibevent::Watcher {
 public:
  Helper(base::PlatformFile platform_file,
         const HidDeviceInfo& device_info,
         base::WeakPtr<HidConnectionLinux> connection,
         scoped_refptr<base::SingleThreadTaskRunner> task_runner)
      : platform_file_(platform_file),
        connection_(connection),
        task_runner_(task_runner) {
    // Report buffers must always have room for the report ID.
    report_buffer_size_ = device_info.max_input_report_size + 1;
    has_report_id_ = device_info.has_report_id;
  }

  virtual ~Helper() { DCHECK(thread_checker_.CalledOnValidThread()); }

  // Starts the FileDescriptorWatcher that reads input events from the device.
  // Must be called on a thread that has a base::MessageLoopForIO. The helper
  // object is owned by the thread where it was started.
  void Start() {
    base::ThreadRestrictions::AssertIOAllowed();
    thread_checker_.DetachFromThread();
    if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
            platform_file_, true, base::MessageLoopForIO::WATCH_READ,
            &file_watcher_, this)) {
      LOG(ERROR) << "Failed to start watching device file.";
    }
  }

 private:
  // base::MessagePumpLibevent::Watcher implementation.
  void OnFileCanReadWithoutBlocking(int fd) override {
    DCHECK(thread_checker_.CalledOnValidThread());
    DCHECK_EQ(fd, platform_file_);

    scoped_refptr<net::IOBuffer> buffer(new net::IOBuffer(report_buffer_size_));
    char* data = buffer->data();
    size_t length = report_buffer_size_;
    if (!has_report_id_) {
      // Linux will not prefix the buffer with a report ID if report IDs are not
      // used by the device. Prefix the buffer with 0.
      *data++ = 0;
      length--;
    }

    ssize_t bytes_read = HANDLE_EINTR(read(platform_file_, data, length));
    if (bytes_read < 0) {
      if (errno == EAGAIN) {
        return;
      }
      VPLOG(1) << "Read failed";
      return;
    }
    if (!has_report_id_) {
      // Behave as if the byte prefixed above as the the report ID was read.
      bytes_read++;
    }

    task_runner_->PostTask(FROM_HERE,
                           base::Bind(&HidConnectionLinux::ProcessInputReport,
                                      connection_, buffer, bytes_read));
  }
<commit_msg>Catch HID read errors on Linux and stop listening.<commit_after>// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/hid/hid_connection_linux.h"

#include <errno.h>
#include <linux/hidraw.h>
#include <sys/ioctl.h>

#include <string>

#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_pump_libevent.h"
#include "base/posix/eintr_wrapper.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/thread_restrictions.h"
#include "device/hid/hid_service.h"

// These are already defined in newer versions of linux/hidraw.h.
#ifndef HIDIOCSFEATURE
#define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE | _IOC_READ, 'H', 0x06, len)
#endif
#ifndef HIDIOCGFEATURE
#define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE | _IOC_READ, 'H', 0x07, len)
#endif

namespace device {

class HidConnectionLinux::Helper : public base::MessagePumpLibevent::Watcher {
 public:
  Helper(base::PlatformFile platform_file,
         const HidDeviceInfo& device_info,
         base::WeakPtr<HidConnectionLinux> connection,
         scoped_refptr<base::SingleThreadTaskRunner> task_runner)
      : platform_file_(platform_file),
        connection_(connection),
        task_runner_(task_runner) {
    // Report buffers must always have room for the report ID.
    report_buffer_size_ = device_info.max_input_report_size + 1;
    has_report_id_ = device_info.has_report_id;
  }

  virtual ~Helper() { DCHECK(thread_checker_.CalledOnValidThread()); }

  // Starts the FileDescriptorWatcher that reads input events from the device.
  // Must be called on a thread that has a base::MessageLoopForIO. The helper
  // object is owned by the thread where it was started.
  void Start() {
    base::ThreadRestrictions::AssertIOAllowed();
    thread_checker_.DetachFromThread();
    if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
            platform_file_, true, base::MessageLoopForIO::WATCH_READ,
            &file_watcher_, this)) {
      LOG(ERROR) << "Failed to start watching device file.";
    }
  }

 private:
  // base::MessagePumpLibevent::Watcher implementation.
  void OnFileCanReadWithoutBlocking(int fd) override {
    DCHECK(thread_checker_.CalledOnValidThread());
    DCHECK_EQ(fd, platform_file_);

    scoped_refptr<net::IOBuffer> buffer(new net::IOBuffer(report_buffer_size_));
    char* data = buffer->data();
    size_t length = report_buffer_size_;
    if (!has_report_id_) {
      // Linux will not prefix the buffer with a report ID if report IDs are not
      // used by the device. Prefix the buffer with 0.
      *data++ = 0;
      length--;
    }

    ssize_t bytes_read = HANDLE_EINTR(read(platform_file_, data, length));
    if (bytes_read < 0) {
      if (errno != EAGAIN) {
        VPLOG(1) << "Read failed";
        // This assumes that the error is unrecoverable and disables reading
        // from the device until it has been re-opened.
        // TODO(reillyg): Investigate starting and stopping the file descriptor
        // watcher in response to pending read requests so that per-request
        // errors can be returned to the client.
        file_watcher_.StopWatchingFileDescriptor();
      }
      return;
    }
    if (!has_report_id_) {
      // Behave as if the byte prefixed above as the the report ID was read.
      bytes_read++;
    }

    task_runner_->PostTask(FROM_HERE,
                           base::Bind(&HidConnectionLinux::ProcessInputReport,
                                      connection_, buffer, bytes_read));
  }

{'fraction_non_alphanumeric': 0.10298142013538816, 'fraction_numerical': 0.004320898746939364, 'mean_word_length': 3.5120207927225473, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4420763', 'n_tokens_mistral': 2179, 'n_tokens_neox': 2164, 'n_words': 565}