LoginSignup
6
6

More than 5 years have passed since last update.

Mechanizeでsecure.nicovideo.jpに繋ぐ

Posted at

ニコ動関連の小さなツールを作ってたんだけど、Ruby 2.0に上げてから動かなくなって放置していたのを久しぶりに調べてみた。

https://bugs.ruby-lang.org/issues/8590
パッチを見ると、net/httpの@ssl_sessionをnilにできればなんとかなりそう。
取り込まれていない理由は、ssl力が足らなくて議論の内容をちゃんと把握できてないのだけど、もっとちゃんとした方法の修正があるのだと思う。

で、とりあえずworkaroundが出来たので貼っておく。Mechanizeとnet/httpの間にはもう一個、net-http-persistentというgemが挟まっているので、それに対してRuby 2.xのModule#prependを使ってモンキーパッチしている。

require 'mechanize'
require 'logger'

class Net::HTTP::Persistent
  module DisableSslReuse
    def connection_for(uri)
      connection = super
      connection.instance_variable_set(:@ssl_session, nil)
      return connection
    end
  end

  prepend DisableSslReuse   # この行を外すとタイムアウトする
end

agent = Mechanize.new
agent.ssl_version = 'TLSv1'
agent.log = Logger.new(STDOUT)
p @agent.get('https://secure.nicovideo.jp')

Module#prependを使うと、本来のconnection_forより前にモンキーパッチのconnection_forが呼ばれるようになる。パッチ内ではsuperを使うことでもとのメソッドを呼び出せる。

6
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6