SlideShare uma empresa Scribd logo
1 de 32
The Ruby Guide to
*nix Plumbing
on the quest for efficiency with Ruby [M|K]RI


http://slides.games-with-brains.net
who am I?
               Eleanor McHugh
            eleanor@games-with-brains.com
                 twitter.com/feyeleanor


             usual haunts include
                    ruby-talk
                      LRUG
                     devchix
               ruby conferences
hacker 101

every unix hacker was once a clueless noob
who learnt their craft through experimentation
today I hope to whet your appetite
by showing you reams of broken code
fixing it is an exercise for the reader
and one well worth the sweat and tears
common requirements
access native hardware
“real-time” user interaction
scale to suit demand
that’s systems programming
and it’s our right as coders to get low-level in
whichever language best suits our needs
but unix is all about C...
that’s like saying web development is all about
javascript - it may be a daily experience but it’s
far from immutable truth
no, unix is about the kernel
which was originally implemented in C with a jus
of assembler, hence the confusion
we can script that in ruby
C is just one language for scripting the kernel
but anything you can do in C you can do in ruby,
python, groovy, scheme, assembler
all you need is a syscall function and some
magic numbers
unix bootcamp
the kernel manages resources
a process is a program execution
a file stores sequences of character data
a block device describes a peripheral
a signal is a software interrupt
knife goes in...
only build what we need
reuse what we already have
change our tools as [des|requ]ired
stay flexible
...guts come out
cohesive device model
kernel to manage resources
shell for user interaction
userspace partitions risk
everything else is plumbing
hierarchical trees & files
users & permissions
processes, signals & communications
do with it what you will
“if you give people the license to be as
outrageous as they want in absolutely any
fashion they can dream up, they’ll be creative
about it, and do something good besides”
                                    - Lester Bangs
accessing kernel resources
Kernel#syscall & kernel function indices
file descriptors
IO#for_fd
require 'fcntl'
filemode = Fcntl::O_CREAT | Fcntl::O_RDWR | Fcntl::O_APPEND
descriptor = IO.sysopen “test.dat”, filemode
file = IO.new descriptor
file.syswrite “hello”
file.sysseek 0
$stdout.puts file.sysread(10)

produces:
  hello
ruby/dl
dynamic libraries
managed memory buffers
ruby callbacks
wrapping c syscall
require ‘dl’                                            file = open “test.dat”, 0x0209
CRT = DL.dlopen ‘libc.dylib’                            write file, “textn”
F = ‘syscall’                                           close file

def open file, mode                                      file = open “test.dat”, 0x0000
     CRT[F, ‘IISI’].call(5, file, mode)[0]               text = read file, 10
end                                                     close file

def write fd, string, bytes = string.length
    CRT[F, ‘IIISI’].call(4, fd, string, bytes)[0]
end

def read fd, bytes = 1
     buffer = DL.malloc(bytes)
     CRT[F, ‘IIIsI’].call(3, fd, buffer, bytes)[1][2]
end

def close fd
     CRT[F, ‘III’].call(6, fd)[0]
end
malloc
DL:PtrData
garbage collection with free and realloc
[String|Array]#to_ptr
PtrData#[struct|union]!
works how you expect
require ‘dl’

memory_buffer = DL::malloc 20
=> #<DL::PtrData:0x2d0870 ptr=0x820600 size=20 free=0x1b0257>

memory_buffer[0] = “hello world!”
=> “hello world!000000000000000000000000"

memory_buffer.free
=> #<DL::Symbol:0x40b760 func=0x1b0257 'void (free)(void *);'>

memory_buffer.nil
=> nil
most of the time
string = “hello ruby”
memory_buffer = string.to_ptr
=> #<DL::PtrData:0x41bea0 ptr=0x41be60 size=10 free=0x1b0257>

memory_buffer[0] = “goodbye world”
memory_buffer += 1
=> #<DL::PtrData:0x422000 ptr=0x41be61 size=9 free=0x0>

puts memory_buffer, memory_buffer.to_str, string
=> “oodbye world”
=> “oodbye wo”
=> “hello ruby”

memory_buffer -= 1
=> (irb):51: [BUG] Segmentation fault
the callback that never was
require 'dl'
SIGSEGV = DL::dlopen('libsigsegv.dylib')
install_handler = SIGSEGV['sigsegv_install_handler', 'IP']
deinstall_handler = SIGSEGV['sigsegv_deinstall_handler', '0']
leave_handler = SIGSEGV['sigsegv_leave_handler', 'IPPPP']

continuation = DL.callback('IPPP') do |address, b, c|
 raise RuntimeError, "segfault at #{address}"
end

handler = DL.callback('IPI') do |fault_address, serious|
 leave_handler.call continuation, fault_address, nil, nil
end

install_handler.call handler
multi-tasking
threads & processes
semaphores & interprocess communications
shared memory
multiple cores
leveraging networks
limitations of ruby threads
green threads
pthreads
the global interpreter lock
pthreads and child processes
the FreeBSD conundrum
threaded socket I/O
require 'socket'                                                    def serve request
require 'thread'                                                     ["hello", 0]
require 'mutex_m'                                                   end

class UDPServer                                                    private
 include Mutex_m                                                    def event_loop
 attr_reader :address, :port, :log                                    loop do
                                                                        if sockets = select([@socket]) then
 def initialize address, port                                             sockets[0].each do |s|
  @address, @port = address, port                                           @workers << Thread.new(s) do |socket|
  @workers = []                                                              message, peer = *socket.recvfrom 512
 end                                                                         reply, status = *serve message
                                                                             UDPSocket.open.send reply, status, peer[2], peer[1]
 def start                                                                  end
  @socket = UDPSocket.new                                                 end
  @socket.bind @address, @port                                            @workers.compact!
  @socket.setsockopt Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1        end
  event_loop                                                          end
 end                                                                end
                                                                   end
 def stop
  @workers.each { |thread| thread.kill }
  lock
    @socket.close
    @socket = nil
  unlock
 end
fork and be damned
require 'socket'                                                   private
                                                                    def event_loop
class UDPForkingServer                                                loop do
 attr_reader :address, :port, :log                                      if sockets = select([@socket]) then
                                                                          sockets[0].each do |s|
 def initialize address, port                                               fork
  @address, @port = address, port                                             message, peer = *socket.recvfrom(512)
 end                                                                          reply, status = *serve message
                                                                              UDPSocket.open.send reply, status, peer[2], peer[1]
 def start                                                                  end
  @socket = UDPSocket.new                                                 end
  @socket.bind @address, @port                                          end
  @socket.setsockopt Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1      end
  event_loop                                                        end
 end                                                               end

 def stop
  @socket.close
  @socket = nil
 end

 def serve request
  ["hello", 0]
 end
arbitrating sequence
  require ‘dl’
  require ‘fcntl’
  LIBC = DL::dlopen ‘libc.dylib’
  open = LIBC[‘sem_open’, ‘ISII’]
  try_wait = LIBC[‘sem_trywait’, ‘II’]
  wait = LIBC[‘sem_wait’, ‘II’]
  post = LIBC[‘sem_post’, ‘II’]
  close = LIBC[‘sem_close’, ‘II’]


process 1                                            process 2
  s = open.call(“/tmp/s”, Fcntl::O_CREAT, 1911)[0]     s = open.call(“/tmp/s”)
  wait.call s                                          t = Time.now
  puts “locked at #{Time.now}”                         if try_wait.call(s)[0] == 0 then
  sleep 50                                                   puts “locked at #{t}”
  puts “posted at #{Time.now}”                         else
  post.call s                                                puts “busy at #{t}”
  close.call s                                               wait.call s
                                                             puts “waited #{Time.now - t} seconds”
  => locked at Thu May 28 01:03:23 +0100 2009          end
  => posted at Thu May 28 01:04:13 +0100 2009
                                                       => busy at Thu May 28 01:03:36 +0100 2009
                                                       => waited 47.056508 seconds
law of diminishing returns
2x the cores never means 2x the performance
this is fundamental communications theory
and applies to all “real-time” systems
including your development processes...
leverage Shannon-Nyquist to your advantage
pipes & sockets
point-to-point links between processes
pipes are restricted to the local machine
sockets can be local or remote
the fifo is a multiway pipe for special occasions
the fifo - a persistent pipe
process 1                                     process 2

  File.umask 0                                File.umask 0
  MKFIFO = 132                                MKFIFO = 132
  syscall MKFIFO, fifo_name, 0666              syscall MKFIFO, “client”, 0666
  fd = IO.sysopen “server”, File::RDONLY      fd = IO.sysopen "server", File::WRONLY
  server = File.new fd, "r"                   server = IO.new fd, "w"
  client_name = server.gets.chomp             server.puts fifo_name
  puts "#{Time.now}: [#{client_name}]"        server.puts "hello world!"
  fd = IO.sysopen client_name, File::WRONLY   server.close
  client = IO.new fd, "w"                     fd = IO.sysopen “client”, File::RDONLY
  message = server.gets.chomp                 client = IO.new fd, "r"
  client.puts message.reverse                 puts client.gets
  client.close                                client.close
  server.close                                File.delete “client”
  File.delete “server”
sharing memory
allows processes to share data directly
no need to bother with sockets or pipes
but concurrency becomes a major concern
another exciting use for semaphores
beyond ruby/dl
ruby-ffi
RubyInline
wilson
the plumber’s reading list

 http://slides.games-with-brains.net

 http://www.jbrowse.com/text/rdl_en.html

 http://www.kegel.com/c10k.html

 http://www.ecst.csuchico.edu/~beej/guide/ipc/

 http://beej.us/guide/bgnet/

 http://wiki.netbsd.se/kqueue_tutorial

Mais conteúdo relacionado

Mais procurados

ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programmingAnung Ariwibowo
 
Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)Flor Ian
 
Distributed Data Structures
Distributed Data StructuresDistributed Data Structures
Distributed Data StructuresPDX Web & Design
 
Creating an Arduino Web Server from scratch hardware and software
Creating an Arduino Web Server from scratch hardware and softwareCreating an Arduino Web Server from scratch hardware and software
Creating an Arduino Web Server from scratch hardware and softwareJustin Mclean
 
How to stand on the shoulders of giants
How to stand on the shoulders of giantsHow to stand on the shoulders of giants
How to stand on the shoulders of giantsIan Barber
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014Fantix King 王川
 
How to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyHow to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyVMware Tanzu
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency명신 김
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineMovel
 
Playing 44CON CTF for fun and profit
Playing 44CON CTF for fun and profitPlaying 44CON CTF for fun and profit
Playing 44CON CTF for fun and profit44CON
 
Study of aloha protocol using ns2 network java proram
Study of aloha protocol using ns2 network java proramStudy of aloha protocol using ns2 network java proram
Study of aloha protocol using ns2 network java proramMeenakshi Devi
 

Mais procurados (20)

ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
Binomial heap
Binomial heapBinomial heap
Binomial heap
 
Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)
 
Distributed Data Structures
Distributed Data StructuresDistributed Data Structures
Distributed Data Structures
 
Creating an Arduino Web Server from scratch hardware and software
Creating an Arduino Web Server from scratch hardware and softwareCreating an Arduino Web Server from scratch hardware and software
Creating an Arduino Web Server from scratch hardware and software
 
How to stand on the shoulders of giants
How to stand on the shoulders of giantsHow to stand on the shoulders of giants
How to stand on the shoulders of giants
 
Usp
UspUsp
Usp
 
part2
part2part2
part2
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
Introducing to Asynchronous Programming
Introducing to Asynchronous  ProgrammingIntroducing to Asynchronous  Programming
Introducing to Asynchronous Programming
 
How to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyHow to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor Netty
 
Sockets intro
Sockets introSockets intro
Sockets intro
 
Ns2programs
Ns2programsNs2programs
Ns2programs
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
Playing 44CON CTF for fun and profit
Playing 44CON CTF for fun and profitPlaying 44CON CTF for fun and profit
Playing 44CON CTF for fun and profit
 
Study of aloha protocol using ns2 network java proram
Study of aloha protocol using ns2 network java proramStudy of aloha protocol using ns2 network java proram
Study of aloha protocol using ns2 network java proram
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Rust-lang
Rust-langRust-lang
Rust-lang
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
 

Semelhante a The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI

Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsAnchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsEleanor McHugh
 
An (abridged) Ruby Plumber's Guide to *nix
An (abridged) Ruby Plumber's Guide to *nixAn (abridged) Ruby Plumber's Guide to *nix
An (abridged) Ruby Plumber's Guide to *nixEleanor McHugh
 
Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011David Troy
 
it's only abuse if it crashes
it's only abuse if it crashesit's only abuse if it crashes
it's only abuse if it crashesEleanor McHugh
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptsenthilnathans25
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureAmaury Bouchard
 
Concurrency: Rubies, Plural
Concurrency: Rubies, PluralConcurrency: Rubies, Plural
Concurrency: Rubies, PluralEleanor McHugh
 
Concurrency: Rubies, plural
Concurrency: Rubies, pluralConcurrency: Rubies, plural
Concurrency: Rubies, pluralehuard
 
drb09
drb09drb09
drb09mseki
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیMohammad Reza Kamalifard
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdfsecunderbadtirumalgi
 
Rust: Reach Further
Rust: Reach FurtherRust: Reach Further
Rust: Reach Furthernikomatsakis
 

Semelhante a The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI (20)

Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsAnchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
 
An (abridged) Ruby Plumber's Guide to *nix
An (abridged) Ruby Plumber's Guide to *nixAn (abridged) Ruby Plumber's Guide to *nix
An (abridged) Ruby Plumber's Guide to *nix
 
Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011
 
it's only abuse if it crashes
it's only abuse if it crashesit's only abuse if it crashes
it's only abuse if it crashes
 
sockets_intro.ppt
sockets_intro.pptsockets_intro.ppt
sockets_intro.ppt
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
 
Computer networkppt4577
Computer networkppt4577Computer networkppt4577
Computer networkppt4577
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heure
 
Npc08
Npc08Npc08
Npc08
 
Concurrency: Rubies, Plural
Concurrency: Rubies, PluralConcurrency: Rubies, Plural
Concurrency: Rubies, Plural
 
Concurrency: Rubies, plural
Concurrency: Rubies, pluralConcurrency: Rubies, plural
Concurrency: Rubies, plural
 
drb09
drb09drb09
drb09
 
Python networking
Python networkingPython networking
Python networking
 
lab04.pdf
lab04.pdflab04.pdf
lab04.pdf
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
 
Rust: Reach Further
Rust: Reach FurtherRust: Reach Further
Rust: Reach Further
 
Npc14
Npc14Npc14
Npc14
 
10 Networking
10 Networking10 Networking
10 Networking
 

Mais de Eleanor McHugh

[2023] Putting the R! in R&D.pdf
[2023] Putting the R! in R&D.pdf[2023] Putting the R! in R&D.pdf
[2023] Putting the R! in R&D.pdfEleanor McHugh
 
Generics, Reflection, and Efficient Collections
Generics, Reflection, and Efficient CollectionsGenerics, Reflection, and Efficient Collections
Generics, Reflection, and Efficient CollectionsEleanor McHugh
 
The Relevance of Liveness - Biometrics and Data Integrity
The Relevance of Liveness - Biometrics and Data IntegrityThe Relevance of Liveness - Biometrics and Data Integrity
The Relevance of Liveness - Biometrics and Data IntegrityEleanor McHugh
 
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]Eleanor McHugh
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveEleanor McHugh
 
Go for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd editionGo for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd editionEleanor McHugh
 
An introduction to functional programming with Go [redux]
An introduction to functional programming with Go [redux]An introduction to functional programming with Go [redux]
An introduction to functional programming with Go [redux]Eleanor McHugh
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with goEleanor McHugh
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
 
Identity & trust in Monitored Spaces
Identity & trust in Monitored SpacesIdentity & trust in Monitored Spaces
Identity & trust in Monitored SpacesEleanor McHugh
 
Don't Ask, Don't Tell - The Virtues of Privacy By Design
Don't Ask, Don't Tell - The Virtues of Privacy By DesignDon't Ask, Don't Tell - The Virtues of Privacy By Design
Don't Ask, Don't Tell - The Virtues of Privacy By DesignEleanor McHugh
 
Don't ask, don't tell the virtues of privacy by design
Don't ask, don't tell   the virtues of privacy by designDon't ask, don't tell   the virtues of privacy by design
Don't ask, don't tell the virtues of privacy by designEleanor McHugh
 
Anonymity, identity, trust
Anonymity, identity, trustAnonymity, identity, trust
Anonymity, identity, trustEleanor McHugh
 
Going Loopy - Adventures in Iteration with Google Go
Going Loopy - Adventures in Iteration with Google GoGoing Loopy - Adventures in Iteration with Google Go
Going Loopy - Adventures in Iteration with Google GoEleanor McHugh
 
Distributed Ledgers: Anonymity & Immutability at Scale
Distributed Ledgers: Anonymity & Immutability at ScaleDistributed Ledgers: Anonymity & Immutability at Scale
Distributed Ledgers: Anonymity & Immutability at ScaleEleanor McHugh
 
Go for the paranoid network programmer, 2nd edition
Go for the paranoid network programmer, 2nd editionGo for the paranoid network programmer, 2nd edition
Go for the paranoid network programmer, 2nd editionEleanor McHugh
 
Going Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with GoGoing Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with GoEleanor McHugh
 
Finding a useful outlet for my many Adventures in go
Finding a useful outlet for my many Adventures in goFinding a useful outlet for my many Adventures in go
Finding a useful outlet for my many Adventures in goEleanor McHugh
 
Anonymity, trust, accountability
Anonymity, trust, accountabilityAnonymity, trust, accountability
Anonymity, trust, accountabilityEleanor McHugh
 

Mais de Eleanor McHugh (20)

[2023] Putting the R! in R&D.pdf
[2023] Putting the R! in R&D.pdf[2023] Putting the R! in R&D.pdf
[2023] Putting the R! in R&D.pdf
 
Generics, Reflection, and Efficient Collections
Generics, Reflection, and Efficient CollectionsGenerics, Reflection, and Efficient Collections
Generics, Reflection, and Efficient Collections
 
The Relevance of Liveness - Biometrics and Data Integrity
The Relevance of Liveness - Biometrics and Data IntegrityThe Relevance of Liveness - Biometrics and Data Integrity
The Relevance of Liveness - Biometrics and Data Integrity
 
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
 
Go for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd editionGo for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd edition
 
An introduction to functional programming with Go [redux]
An introduction to functional programming with Go [redux]An introduction to functional programming with Go [redux]
An introduction to functional programming with Go [redux]
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with go
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Identity & trust in Monitored Spaces
Identity & trust in Monitored SpacesIdentity & trust in Monitored Spaces
Identity & trust in Monitored Spaces
 
Don't Ask, Don't Tell - The Virtues of Privacy By Design
Don't Ask, Don't Tell - The Virtues of Privacy By DesignDon't Ask, Don't Tell - The Virtues of Privacy By Design
Don't Ask, Don't Tell - The Virtues of Privacy By Design
 
Don't ask, don't tell the virtues of privacy by design
Don't ask, don't tell   the virtues of privacy by designDon't ask, don't tell   the virtues of privacy by design
Don't ask, don't tell the virtues of privacy by design
 
Anonymity, identity, trust
Anonymity, identity, trustAnonymity, identity, trust
Anonymity, identity, trust
 
Going Loopy - Adventures in Iteration with Google Go
Going Loopy - Adventures in Iteration with Google GoGoing Loopy - Adventures in Iteration with Google Go
Going Loopy - Adventures in Iteration with Google Go
 
Distributed Ledgers: Anonymity & Immutability at Scale
Distributed Ledgers: Anonymity & Immutability at ScaleDistributed Ledgers: Anonymity & Immutability at Scale
Distributed Ledgers: Anonymity & Immutability at Scale
 
Hello Go
Hello GoHello Go
Hello Go
 
Go for the paranoid network programmer, 2nd edition
Go for the paranoid network programmer, 2nd editionGo for the paranoid network programmer, 2nd edition
Go for the paranoid network programmer, 2nd edition
 
Going Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with GoGoing Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with Go
 
Finding a useful outlet for my many Adventures in go
Finding a useful outlet for my many Adventures in goFinding a useful outlet for my many Adventures in go
Finding a useful outlet for my many Adventures in go
 
Anonymity, trust, accountability
Anonymity, trust, accountabilityAnonymity, trust, accountability
Anonymity, trust, accountability
 

Último

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 

Último (20)

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 

The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI

  • 1. The Ruby Guide to *nix Plumbing on the quest for efficiency with Ruby [M|K]RI http://slides.games-with-brains.net
  • 2. who am I? Eleanor McHugh eleanor@games-with-brains.com twitter.com/feyeleanor usual haunts include ruby-talk LRUG devchix ruby conferences
  • 3. hacker 101 every unix hacker was once a clueless noob who learnt their craft through experimentation today I hope to whet your appetite by showing you reams of broken code fixing it is an exercise for the reader and one well worth the sweat and tears
  • 4. common requirements access native hardware “real-time” user interaction scale to suit demand
  • 5. that’s systems programming and it’s our right as coders to get low-level in whichever language best suits our needs
  • 6. but unix is all about C... that’s like saying web development is all about javascript - it may be a daily experience but it’s far from immutable truth
  • 7. no, unix is about the kernel which was originally implemented in C with a jus of assembler, hence the confusion
  • 8. we can script that in ruby C is just one language for scripting the kernel but anything you can do in C you can do in ruby, python, groovy, scheme, assembler all you need is a syscall function and some magic numbers
  • 9. unix bootcamp the kernel manages resources a process is a program execution a file stores sequences of character data a block device describes a peripheral a signal is a software interrupt
  • 10. knife goes in... only build what we need reuse what we already have change our tools as [des|requ]ired stay flexible
  • 11. ...guts come out cohesive device model kernel to manage resources shell for user interaction userspace partitions risk
  • 12. everything else is plumbing hierarchical trees & files users & permissions processes, signals & communications
  • 13. do with it what you will “if you give people the license to be as outrageous as they want in absolutely any fashion they can dream up, they’ll be creative about it, and do something good besides” - Lester Bangs
  • 14. accessing kernel resources Kernel#syscall & kernel function indices file descriptors IO#for_fd
  • 15. require 'fcntl' filemode = Fcntl::O_CREAT | Fcntl::O_RDWR | Fcntl::O_APPEND descriptor = IO.sysopen “test.dat”, filemode file = IO.new descriptor file.syswrite “hello” file.sysseek 0 $stdout.puts file.sysread(10) produces: hello
  • 17. wrapping c syscall require ‘dl’ file = open “test.dat”, 0x0209 CRT = DL.dlopen ‘libc.dylib’ write file, “textn” F = ‘syscall’ close file def open file, mode file = open “test.dat”, 0x0000 CRT[F, ‘IISI’].call(5, file, mode)[0] text = read file, 10 end close file def write fd, string, bytes = string.length CRT[F, ‘IIISI’].call(4, fd, string, bytes)[0] end def read fd, bytes = 1 buffer = DL.malloc(bytes) CRT[F, ‘IIIsI’].call(3, fd, buffer, bytes)[1][2] end def close fd CRT[F, ‘III’].call(6, fd)[0] end
  • 18. malloc DL:PtrData garbage collection with free and realloc [String|Array]#to_ptr PtrData#[struct|union]!
  • 19. works how you expect require ‘dl’ memory_buffer = DL::malloc 20 => #<DL::PtrData:0x2d0870 ptr=0x820600 size=20 free=0x1b0257> memory_buffer[0] = “hello world!” => “hello world!000000000000000000000000" memory_buffer.free => #<DL::Symbol:0x40b760 func=0x1b0257 'void (free)(void *);'> memory_buffer.nil => nil
  • 20. most of the time string = “hello ruby” memory_buffer = string.to_ptr => #<DL::PtrData:0x41bea0 ptr=0x41be60 size=10 free=0x1b0257> memory_buffer[0] = “goodbye world” memory_buffer += 1 => #<DL::PtrData:0x422000 ptr=0x41be61 size=9 free=0x0> puts memory_buffer, memory_buffer.to_str, string => “oodbye world” => “oodbye wo” => “hello ruby” memory_buffer -= 1 => (irb):51: [BUG] Segmentation fault
  • 21. the callback that never was require 'dl' SIGSEGV = DL::dlopen('libsigsegv.dylib') install_handler = SIGSEGV['sigsegv_install_handler', 'IP'] deinstall_handler = SIGSEGV['sigsegv_deinstall_handler', '0'] leave_handler = SIGSEGV['sigsegv_leave_handler', 'IPPPP'] continuation = DL.callback('IPPP') do |address, b, c| raise RuntimeError, "segfault at #{address}" end handler = DL.callback('IPI') do |fault_address, serious| leave_handler.call continuation, fault_address, nil, nil end install_handler.call handler
  • 22. multi-tasking threads & processes semaphores & interprocess communications shared memory multiple cores leveraging networks
  • 23. limitations of ruby threads green threads pthreads the global interpreter lock pthreads and child processes the FreeBSD conundrum
  • 24. threaded socket I/O require 'socket' def serve request require 'thread' ["hello", 0] require 'mutex_m' end class UDPServer private include Mutex_m def event_loop attr_reader :address, :port, :log loop do if sockets = select([@socket]) then def initialize address, port sockets[0].each do |s| @address, @port = address, port @workers << Thread.new(s) do |socket| @workers = [] message, peer = *socket.recvfrom 512 end reply, status = *serve message UDPSocket.open.send reply, status, peer[2], peer[1] def start end @socket = UDPSocket.new end @socket.bind @address, @port @workers.compact! @socket.setsockopt Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1 end event_loop end end end end def stop @workers.each { |thread| thread.kill } lock @socket.close @socket = nil unlock end
  • 25. fork and be damned require 'socket' private def event_loop class UDPForkingServer loop do attr_reader :address, :port, :log if sockets = select([@socket]) then sockets[0].each do |s| def initialize address, port fork @address, @port = address, port message, peer = *socket.recvfrom(512) end reply, status = *serve message UDPSocket.open.send reply, status, peer[2], peer[1] def start end @socket = UDPSocket.new end @socket.bind @address, @port end @socket.setsockopt Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1 end event_loop end end end def stop @socket.close @socket = nil end def serve request ["hello", 0] end
  • 26. arbitrating sequence require ‘dl’ require ‘fcntl’ LIBC = DL::dlopen ‘libc.dylib’ open = LIBC[‘sem_open’, ‘ISII’] try_wait = LIBC[‘sem_trywait’, ‘II’] wait = LIBC[‘sem_wait’, ‘II’] post = LIBC[‘sem_post’, ‘II’] close = LIBC[‘sem_close’, ‘II’] process 1 process 2 s = open.call(“/tmp/s”, Fcntl::O_CREAT, 1911)[0] s = open.call(“/tmp/s”) wait.call s t = Time.now puts “locked at #{Time.now}” if try_wait.call(s)[0] == 0 then sleep 50 puts “locked at #{t}” puts “posted at #{Time.now}” else post.call s puts “busy at #{t}” close.call s wait.call s puts “waited #{Time.now - t} seconds” => locked at Thu May 28 01:03:23 +0100 2009 end => posted at Thu May 28 01:04:13 +0100 2009 => busy at Thu May 28 01:03:36 +0100 2009 => waited 47.056508 seconds
  • 27. law of diminishing returns 2x the cores never means 2x the performance this is fundamental communications theory and applies to all “real-time” systems including your development processes... leverage Shannon-Nyquist to your advantage
  • 28. pipes & sockets point-to-point links between processes pipes are restricted to the local machine sockets can be local or remote the fifo is a multiway pipe for special occasions
  • 29. the fifo - a persistent pipe process 1 process 2 File.umask 0 File.umask 0 MKFIFO = 132 MKFIFO = 132 syscall MKFIFO, fifo_name, 0666 syscall MKFIFO, “client”, 0666 fd = IO.sysopen “server”, File::RDONLY fd = IO.sysopen "server", File::WRONLY server = File.new fd, "r" server = IO.new fd, "w" client_name = server.gets.chomp server.puts fifo_name puts "#{Time.now}: [#{client_name}]" server.puts "hello world!" fd = IO.sysopen client_name, File::WRONLY server.close client = IO.new fd, "w" fd = IO.sysopen “client”, File::RDONLY message = server.gets.chomp client = IO.new fd, "r" client.puts message.reverse puts client.gets client.close client.close server.close File.delete “client” File.delete “server”
  • 30. sharing memory allows processes to share data directly no need to bother with sockets or pipes but concurrency becomes a major concern another exciting use for semaphores
  • 32. the plumber’s reading list http://slides.games-with-brains.net http://www.jbrowse.com/text/rdl_en.html http://www.kegel.com/c10k.html http://www.ecst.csuchico.edu/~beej/guide/ipc/ http://beej.us/guide/bgnet/ http://wiki.netbsd.se/kqueue_tutorial