34 Commits 39babc2547 ... 0088eadeb7

Author SHA1 Message Date
  Federico Amedeo Izzo 0088eadeb7 Added recent work 7 years ago
  Federico Amedeo Izzo 55eba727ac Added first embedded system exercize 8 years ago
  Federico Amedeo Izzo b31cf1e3ae modified lesson 12 number, added lesson 13 9 years ago
  Federico Amedeo Izzo 27fa276d80 Added PSR and CS lessons 9 years ago
  Federico Amedeo Izzo 2cf3727003 Added last Piattaforme MOD2 lessons 9 years ago
  Federico Amedeo Izzo fa05855398 Added two computer security lessons 9 years ago
  Federico Amedeo Izzo de810fee8f Added lesson 13 9 years ago
  Federico Amedeo Izzo b85038f24f Added last two PSR MOD1 lessons 9 years ago
  Federico Amedeo Izzo 8fb2958c87 Added CS lesson 9 9 years ago
  Federico Amedeo Izzo 9a3edb5875 Added piattaforme lessons 9 years ago
  Federico Amedeo Izzo 044ef7ac39 Added last two CS lessons 9 years ago
  Federico Amedeo Izzo e61a8c3124 Added 3 lessons of piattaforme 9 years ago
  Federico Amedeo Izzo 8b01f78ee6 Added last PSR MOD2 lesson 9 years ago
  Federico Amedeo Izzo 4bb52cdb94 Added CS lesson 6 and x86 asm notes 9 years ago
  Federico Amedeo Izzo 3aa451b53e Added last two Computer Security lessons 9 years ago
  Federico Amedeo Izzo 46a76dd4bf Added last Verticale lesson 9 years ago
  Federico Amedeo Izzo 80bd2401ba Completed lesson 5 9 years ago
  Federico Amedeo Izzo ab292c6717 Added lesson 3 and lesson 5 template 9 years ago
  Federico Amedeo Izzo fc0b411332 Added lesson 4 piattaforme mod2 9 years ago
  Federico Amedeo Izzo 27042902db Added lesson 6 Piattaforme - Verticale 9 years ago
  Federico Amedeo Izzo a70de2ab7a Table try 2 9 years ago
  Federico Amedeo Izzo 48c8f4bfce Trying to fix tables 9 years ago
  Federico Amedeo Izzo f89525000e Added gitignore for pdf and lesson template 9 years ago
  Federico Amedeo Izzo 3a01a30cf2 Merge branch 'master' of 212.47.248.194:Nimayer/polimd 9 years ago
  Federico Amedeo Izzo 6e4d5314bd Added Computer Security lesson 2 3 9 years ago
  Federico Amedeo Izzo e8ebee7ae3 Added Piattaforme Software MOD1 lessons 9 years ago
  Federico Amedeo Izzo a7977f8e42 Added last Artificial Intelligence lessons 9 years ago
  Federico Amedeo Izzo eb4145578d Added computer security 9 years ago
  Federico Amedeo Izzo 362a103553 Added 2nd lesson PS mod2 9 years ago
  Federico Amedeo Izzo 105e9f08b2 Added first lessons of piattaforme mod1 + mod2 9 years ago
  Federico Amedeo Izzo 783bfeeb8d Merge branch 'master' of http://izzo.ovh:10080/Nimayer/polimd 9 years ago
  Federico Amedeo Izzo 29b16ff4e1 Added first lesson of ACA 9 years ago
  Federico Amedeo Izzo 80927e2ec4 Added scripts for pdf generation 9 years ago
  Federico Amedeo Izzo 171024074d Fixed errors in formulas and document now compiles to latex 9 years ago
85 changed files with 5131 additions and 5 deletions
  1. 1 0
      .gitignore
  2. 82 0
      Advanced Computer Architectures/lesson_01.md
  3. 93 0
      Advanced OS & Embedded Sys/exe_01.md
  4. 54 0
      Advanced OS & Embedded Sys/lesson_01.md
  5. 83 0
      Advanced OS & Embedded Sys/lesson_03.md
  6. 92 0
      Artificial Intelligence/history_01.md
  7. 17 0
      Artificial Intelligence/history_02.md
  8. 1 1
      Artificial Intelligence/lesson_10.md
  9. 30 0
      Artificial Intelligence/lesson_13.md
  10. 130 0
      Computer Ethics/lesson_01.md
  11. 156 0
      Computer Ethics/lesson_02.md
  12. 80 0
      Computer Ethics/lesson_03.md
  13. 79 0
      Computer Ethics/lesson_04.md
  14. 6 0
      Computer Security/genpdf.sh
  15. 93 0
      Computer Security/lesson_01.md
  16. 151 0
      Computer Security/lesson_02.md
  17. 48 0
      Computer Security/lesson_03.md
  18. 41 0
      Computer Security/lesson_04.md
  19. 47 0
      Computer Security/lesson_05.md
  20. 44 0
      Computer Security/lesson_06.md
  21. 78 0
      Computer Security/lesson_07.md
  22. 62 0
      Computer Security/lesson_08.md
  23. 43 0
      Computer Security/lesson_09.md
  24. 49 0
      Computer Security/lesson_10.md
  25. 27 0
      Computer Security/lesson_11.md
  26. 18 0
      Computer Security/lesson_12.md
  27. 103 0
      Computer Security/lesson_13.md
  28. 23 0
      Computer Security/lesson_14.md
  29. 14 0
      Computer Security/lesson_15.md
  30. 44 0
      Computer Security/lesson_16.md
  31. 44 0
      Computer Security/lesson_17.md
  32. 32 0
      Computer Security/lesson_18.md
  33. 32 0
      Computer Security/lesson_19.md
  34. 24 0
      Computer Security/x86_lesson.md
  35. 172 0
      Cryptography/exe_01.md
  36. 12 0
      Cryptography/lesson_01.md
  37. 8 4
      Formal Languages and Compilers/lesson_03.md
  38. BIN
      Game Theory/.lesson_03.md.swp
  39. 23 0
      Game Theory/lesson_03.md
  40. 17 0
      OR/lesson_01.md
  41. BIN
      Piattaforme Software per la Rete/.lesson_04.md.swp
  42. 6 0
      Piattaforme Software per la Rete/MOD1/genpdf.sh
  43. 14 0
      Piattaforme Software per la Rete/MOD1/lesson_00.md
  44. 3 0
      Piattaforme Software per la Rete/MOD1/lesson_01.md
  45. 99 0
      Piattaforme Software per la Rete/MOD1/lesson_02.md
  46. 51 0
      Piattaforme Software per la Rete/MOD1/lesson_03.md
  47. 70 0
      Piattaforme Software per la Rete/MOD1/lesson_04.md
  48. 129 0
      Piattaforme Software per la Rete/MOD1/lesson_05.md
  49. 138 0
      Piattaforme Software per la Rete/MOD1/lesson_06.md
  50. 38 0
      Piattaforme Software per la Rete/MOD1/lesson_07.md
  51. 59 0
      Piattaforme Software per la Rete/MOD1/lesson_08.md
  52. 125 0
      Piattaforme Software per la Rete/MOD1/lesson_09.md
  53. 131 0
      Piattaforme Software per la Rete/MOD1/lesson_10.md
  54. 91 0
      Piattaforme Software per la Rete/MOD1/lesson_11.md
  55. 45 0
      Piattaforme Software per la Rete/MOD1/lesson_12.md
  56. 102 0
      Piattaforme Software per la Rete/MOD1/lesson_13.md
  57. 143 0
      Piattaforme Software per la Rete/MOD1/lesson_14.md
  58. 144 0
      Piattaforme Software per la Rete/MOD1/lesson_15.md
  59. 120 0
      Piattaforme Software per la Rete/MOD1/lesson_16.md
  60. 87 0
      Piattaforme Software per la Rete/MOD1/lesson_17.md
  61. 103 0
      Piattaforme Software per la Rete/MOD1/lesson_18.md
  62. 6 0
      Piattaforme Software per la Rete/MOD2/genpdf.sh
  63. 13 0
      Piattaforme Software per la Rete/MOD2/lesson_00.md
  64. 114 0
      Piattaforme Software per la Rete/MOD2/lesson_01.md
  65. 112 0
      Piattaforme Software per la Rete/MOD2/lesson_02.md
  66. 101 0
      Piattaforme Software per la Rete/MOD2/lesson_03.md
  67. 90 0
      Piattaforme Software per la Rete/MOD2/lesson_04.md
  68. 69 0
      Piattaforme Software per la Rete/MOD2/lesson_05.md
  69. 45 0
      Piattaforme Software per la Rete/MOD2/lesson_06.md
  70. 93 0
      Piattaforme Software per la Rete/MOD2/lesson_07.md
  71. 61 0
      Piattaforme Software per la Rete/MOD2/lesson_08.md
  72. 75 0
      Piattaforme Software per la Rete/MOD2/lesson_09.md
  73. 79 0
      Piattaforme Software per la Rete/MOD2/lesson_10.md
  74. 10 0
      Principles of Programming Languages/lesson_01.md
  75. 135 0
      Segnali/lesson_01.md
  76. 5 0
      lesson_temp.md
  77. 7 0
      makefile
  78. 2 0
      markdown2pdf.sh
  79. 3 0
      markdown2pdf2.sh
  80. 34 0
      polimd_archived/operations_research/lesson_01.md
  81. 97 0
      polimd_archived/operations_research/lesson_02.md
  82. 0 0
      polimd_archived/operations_research/note_follows_on_paper
  83. 95 0
      polimd_archived/soft_computing/lesson_01.md
  84. 34 0
      polimd_archived/soft_computing/lesson_02.md
  85. 0 0
      polimd_archived/soft_computing/note_follows_on_paper

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+*.pdf

+ 82 - 0
Advanced Computer Architectures/lesson_01.md

@@ -0,0 +1,82 @@
+# Advanced Computer Architectures - lesson 1
+#### Cristiana Silvano
+###### 7 March 2016
+## Course Informations
+
+Download on the course sites the slides in advance
+
+## Course Topic
+### Supercomputers
+The most powerful supercomputer in italy is situated in Cineca institute in Bologna.
+Actually the most powerful supercomputer in the world is situated in China
+- __Tianhe-2__ 33.86 PetaFlops on Linpack (benchmark)
+- __Titan__ 17.59 PetaFlops on Linpack (benchmark)
+	- 80'000 NVIDIA Tesla GPUs
+
+### Exascale Supercomputers
+- 20 MW projected to 2023 which requires 50GFlops/W
+	For example Tianhe-2 is only 40th in the consumption list
+The answer to exascale era are Summit and Sierra supercomputers developed in the USA
+
+### The topic of the course will be:
+### Studying cpu architecture for supercomputers, desktop/server and embedded/mobile
+
+### example: Apple A6
+- Introduced in 2012 for the iPhone 5
+- Used Samsung fabrication technology (LoL)
+
+### Apple A9
+- ARMv8 dual core CPU and six-core GPU
+- Competing against Qualcomm Snapdragon 820 and Samsung Exynos 8890
+- Manufactured 14nm by Samung and 16nm by TSMC
+
+### Energy Efficiency
+- This includes squeezing of computer cores in smaller packages
+- Every two year we can double the number of transistors per size
+
+#### We can build multi/may-cores architecture but we cannot switch on all of them together
+This is the __Dark silicon era__ 
+Power consumption and single thread performance are not excalating as density.
+
+### Pipelining in MIPS
+Produced nowadays but Imagination technology (same as PowerVR GPU)
+
+#### MIPS Architecture
+- RISC Instuction set
+- LOAD/STORE Architecture, cannot operate directly on memory (need to load on registers)
+```
+example from C
+c = a + b;
+a -> $s1
+b -> $s2
+c -> $s3
+
+MIPS assembly
+lw $s1,A($s6)
+lw $s2,B($s6)
+add $s3, $s1, $s2
+sw $s3, C($s6)
+```
+#### Reduced MIPS assembly used:
+- ALU operations
+- LOAD/STORE
+- branch/jump
+
+### ALU instructions
+__R-format__
+|op|rs|rt|rd|shamt|funct|
+|---|---|---|---|---|---|
+__I-format__
+|op|rs|rt|immediate|
+|---|---|---|---|
+|6bit|5bit|5bit|16bits|
+
+### Load/Store instructions
+__R-format__
+|op|rs|rt|rd|shamt|funct|
+|---|---|---|---|---|---|
+__I-format__
+|op|rs|rt|offset|
+|---|---|---|---|
+|6bit|5bit|5bit|16bits|
+

+ 93 - 0
Advanced OS & Embedded Sys/exe_01.md

@@ -0,0 +1,93 @@
+# Advanced Operating Systems and Embedded Systems - exercise session 1
+#### Davide Zoni
+###### 13 October 2016
+## Embedded Systems - Multicore Design
+### Course structure
+Multi core architectures require an interconnection layer to be exploited fully.
+
+The course is structured in three parts:
+- On chip communication
+- Architectural simulation
+    Used to test architectural solutions without designing a complete RTL architecture.
+- RTL Design Verification and Simulation
+
+This course will be focused mainly on the power requirements, not covering power, reliability and timing
+for lack of time.
+
+__Exam structure__
+Written exam: 23 points
+Project + presentation: 9 points
+
+## Multi-core history
+From 2000-2005 the CPUs development began hitting the "frequency wall"
+And the power consumption and single thread performance limits aswell.
+
+But the market demands for more processing power, so the response
+was development of the multi-core architecture.
+
+#### Market and Energy Efficiency
+We have two conflicting needs.
+The market asks for devices that are able to run the same applications no
+matter what the underlying hardware.
+while the technology viewpoint says that on mobile phones we have limited resources,
+for example battery, so it's not easy to raise performance.
+
+__Reference book__: Low Power Methodology Manual, ARM&Synopsis, 2007
+
+Halving the size of transistor does not halve the power consumption,
+so reducing size brings to increasing the power density.
+
+## Realiability
+
+#### Escape Bugs:
+They are bugs that ship with the device, due to improper design, and they produce
+a different results from the specification.
+Simple architectures have less escape bugs, and usually the number rises as user discovers them.
+#### Hard Faults:
+Hardware damage due to not proper usage, ex: overvolting.
+
+To test an architecture for escape bugs you have to try all the inputs for all the possible states, because
+usually the CPUs are not *stateless*
+5Million flip-flops means 2^5million states.
+Usually __Bug Inspection__ is done partitioning the design and testing the more common states to be bug-free
+This testing is constrained by time-to-market. But later the verified portion can be expanded.
+
+### Multi-cores
+In general it is more likely to have multiple applications using few resuources, than a single application
+using more resources.
+
+## On-chip interconnects
+Usually the main types of traffic on *on-chip interconnections* are:
+- Data from *load* and *store* OPs
+- Data for cache coherence.
+
+### Different Architectures
+- __Point-to-point__ Used by intel since 2010 in i5 CPUs
+It is fast and simple but grows with n\*(n-1) to the number of cores
+
+- __Bus__ Simple but usually need a split architectures, for example a bus between
+CPU+L1 and L2 and a slower one between L2 and memory.
+
+- __Crossbar__ is a non-blocking architectures until two sender are reaching the same destination
+or vice versa.
+The crossbar is no more than a *multi-bus* architecture, it can be *full* or not.
+The idea is that the more bus used, the more power consumption we have.
+
+- __Network-on-chip__:
+
+
+## On-chip Bus Architecture
+The bus is manager by an __arbiter__ that is not shown usually on schemes.
+
+The bus is not a single line/wire a shown in theory
+In fact there are three different architectures:
+- Tri-state: 
+- AndOr: 
+- Mux: is the most common, it does not have native broadcast support, it can scale better
+but if i want to send a broadcast message (ex: for snooping) i have to consume more power.
+
+The BUS is the ideally placed in the between of the cores, to reduce the length of the wires.
+The BUS has also to avoid __deadlock__ situations.
+
+A __bridge__ is a piece of hardware that interfaces two different communication protocols.
+

+ 54 - 0
Advanced OS & Embedded Sys/lesson_01.md

@@ -0,0 +1,54 @@
+# Advanced Operating Systems and Embedded Systems - lesson 1
+#### William Fornaciari
+###### 4 October 2016
+## Introduction
+
+Website of the last year for slides.
+
+Cinch box -> very rugged, 70€
+
+## Embedded Systems
+Usually in the embedded field we have constrained resources with respect to the general purpose world.
+For example:
+- Very few memory/storage/processing power
+- Thermal/power consumption constraints.
+
+It is not so easy to define an __embedded__ architecture, the basic is a Von Neumann model with
+emphasis on sensors/actuators and power constraints.
+
+## Embedded Market Status
+While we still haven't smart houses?
+There is no market, so there is no need.
+
+And also the market is very fragmented because there is no collaboration between brands.
+
+There are some advancements in the *automotive market*
+In 2007 there was balance between the cost of the iron and cost of the electronics in the
+automotive market, nowadays the electronics cost more.
+
+## Application Contexts
+__The four directions are__
+- Nomadic
+- Public Infrastructures
+- Industrial Systems
+- Private Spaces
+__While two recurring needs are__
+- Networking
+- Sensing
+
+## Solutions
+There is not a unique solution, but there are some good or worse solutions.
+For example wifi is not suited for the embedded market, but other technologies like ZigBee and BLE also have limitations.
+
+## Direction
+- Networked
+- Secure
+- Complex:
+   - Giga complexity by nano technology
+   - Complex through heterogeneity
+- Thermal/power control: run-time management of resources.
+
+## Embedded Systems Design
+Field knowledge is necessary so and emb. eng. have to cooperate with domain experts or keep in mind
+notion of physics.
+

+ 83 - 0
Advanced OS & Embedded Sys/lesson_03.md

@@ -0,0 +1,83 @@
+# Advanced Operating Systems and Embedded Systems - lesson 3
+#### William Fornaciari
+###### 11 October 2016
+## Real Time Operating Systems
+### Real time system
+
+Is a system which has to provide a result within a time range
+usually before a *deadline*
+#### Classification
+- __mission critical systems__
+    - tipycally involves safety
+    - static allocation of resources 
+- __soft real time__: Best effort performance, if the system underperforms, 
+nobody dies but we have a loss of quality
+
+In a system like windows OS, a general delay from an event like mouse movement
+and the reaction takes 200ms, while is a __RTOS__ this time needs to be under 10ms.
+
+#### Charachteristics required for a RTOS
+- __Deterministic behaviour__: operations are executed ad predetermined times or intervals
+- __Responsiveness__: involves minimum interrupt latency, and is due to the fact that
+usually RTOS systems are part of control loops, and the speed of the control system
+needs to be some tipically 5 times the speed of the system.
+Measures to guarantee fast ISR time include:
+    - Inhibiting nested routines
+    - Calling ISR without context switching
+- __User control__: User should have a much more specific control on applications
+w.r.t. ordinary OS
+- __Reliability__: The worst case is to have a blue screen where everything stops.
+A much less worse case is to have a graceful degradation of the performances,
+an example is the thermal throttling of the CPUs when overheating.
+
+For example in the case of a washing machine, in case of a power loss we have 30-100ms
+before the capacitors discharge, to save the content of RAM to a permanent memory.
+This behaviour is called __fail-soft__ and consists of preserving as much data
+ad possible in case of failure.
+
+#### RTOS Features
+- Low cost, small size: usually they employ open-source code.
+- ~20 tasks usually required for an embedded project.
+- Use of *semaphors* for fast access protection.
+- A general paradigm for fast access is *shared memory* protected by *semaphors*
+- For choosing __schedulers__ predictability is preferred over complexity,
+because of this generally used schedulers are *FIFO* or *round robin*
+
+#### Time Constraints
+The "ready" event (process woke up for receiving data) may be:
+- __periodic__: for example sampling at fixed rate, ex: 100Hz
+- __aperiodic__ but predictable
+The computation time may be:
+- Fixed in duration
+- Variable
+- Unpredictable: for example human activity with a computer is unpredictable.
+
+#### Deadlines
+- __hard__: the computation must be completed within the limit or there will be
+a __critical error__
+- __soft__: the deadline is expressed as a preference, but is not critical.
+The *criticality* of a Deadline can be expressed by means of a __Value Function__
+
+#### Preemption
+Makes possible to suspend a process when another task needs to be executed
+and and restore the work later.
+
+Different tipes of computation can be *preemptable* or not or, only preemptable
+in a specific part of their execution
+
+Keeping the system in a safe state is costly, a better tradeoff could be
+keeping the system in a safe state only for portions of the time.
+#### Schedulability analisys consist in deciding to accept or not a new process
+to guarantee the safely conclusion of the existing processes.
+Can be carried out:
+- statically: at bootstrap time
+- dinamically: when the process is created
+__Static table driven__ sched. an. is suitable only for mature systems
+when the execution of the processes is known from the project.
+A famous example is the __Rate Monotonic__ analisys
+__Dynamic planning based__: feasibility is determined at runtime
+
+### Design Issues
+A key problem is choosing the process to be __executed next__
+Sometimes using a non-preemptive scheduler makes sense because this
+way you can not take away the resources that you have allocated.

+ 92 - 0
Artificial Intelligence/history_01.md

@@ -0,0 +1,92 @@
+#History of Artificial Intelligence
+
+### Definition
+
+Artificial Intelligence is a discipline with some goals, such as:
+- solving complex problems
+And these goals are reached by *artificial agents* that *think* as humans
+
+There is a lack of unique and universally accepted definition.
+
+A proposed definition is in the following schema
+
+|Think as humans|Think rationally|
+|---|---|
+|Act as humans|Act rationally|
+
+### History
+
+__General Problem Solver__ (or GPS) is a program developed by A. Newell and H. Simon 
+and it is an attempt of reproducing the human ratinal process. 
+__Alan Turing__ wrote a paper "computing machinery and intelligence" that focused not
+only on intellectual processes but mainly in acting processes.
+Turing Test is based on evaluating a machine only looking at its behaviour and not its internals. 
+__Aristotle__ defined human beings as rational animals.
+
+We as human being are constantly feeling the gap between intentions and actions and is
+related to free will (libero arbitrio)
+
+#### Acting rationally
+
+Is explaines by means of a *rational agent* 
+
+### Artificial Intelligence
+
+Is a young and constantly varying discipline, for example in the 1990's making chess playing programs 
+was at the edge of the discipline while now the actual goals are like making a robot move in an unknown space.
+
+AI is also between __Science__ and __Engineering__ while the second part is prevalent today, the first part 
+is the one that give birth to it.
+
+#### The origin
+
+The origin can be reconducted to the tradition of humans trying to create similar of themselves.
+
+- Heron of Alexandria
+Was the first creator of Semiauthomatic machines called autòmatha (Che destano meraviglia)
+And he was both a matemathician and an engineer
+- Ramon Lull: was a philosopher who wanted to build a machine that is able to reproduce the 
+human process of tought, he called this machine "Ars inveniendi veritatem" and
+with this he tried to prove that there is only one truth and this truth is the cristian one.
+
+The important idea that Lull introduces is the necessity of representing our knowledge in a symbolic way
+and deriving knowledge without altering the initial concepts (like modern first order logic)
+
+Lull built this machine and went to north africa to convert muslims using this machine but he got killed there.
+
+Leibniz also tried to create a formal system to obtain truth with a tool (he would have used is to win discussions agains Newton)
+
+Babbage
+
+Boole is the creator of the agebrization of logic, inventing the propositional logic
+
+Frege invented the first order logic while the notation we use today is from Peano
+
+### The precursors
+
+The precursors comes both from 1940 and are the following:
+- Computer Engineering
+The first computers were built like Z3 or Eniac.
+
+- Cybernetics
+Was a discipline devoted to communication and control of regulatory feedbacks both in living being and machines.
+
+The official birth of Artificial Intelligence was at a workshop in summer 1956 and the object was in ten years
+to build a machine that can simulate human learning or intelligence.
+
+In 1969 the neural networks model was heavily criticized by Minsky and as a result had a stop in research
+
+In 1966 during the cold war the fundings were lessened and there was a crisis of artificial intelligence
+The only funded project by the government was machine translation but lacking notions of linguistics, they build only a semantic translator.
+
+After 1969 *Expert systems* were introduced, and were meant as systems supporting human experts in a particular field.
+During this years Language translators were improves as semantic+syntactic.
+
+From 1980 to today AI vecame an industry and the biggest tech companies became interested.
+
+In 1986 neural networks were rediscovered, in particular back-propagation was reinvented by four different research groups.
+This is a type of sub-symbolic approach
+
+The last step introduces the idea of *intelligent agents* and particularly on groups of agents.
+
+

+ 17 - 0
Artificial Intelligence/history_02.md

@@ -0,0 +1,17 @@
+Physical symbolic system describes intelligence as capacity of manipulating symbols following the laws of phisycs.
+
+Computazionalismo
+
+Naturalismo biologico L'intelligenza è legata al wetware (corpo biologico)
+
+Ultimamente si è passati da intelligenza a razionalità considerando da expert systems, 
+cioè sistemi intelligenti ma specializzati a rational agents, che sono più generali.
+
+Fisica di aristotele e fisica di newton in ottica moderna (chiedere articolo)
+
+Minds,Brains and Programs, Searle's, 1980
+
+CACM M.Vardi editoriale su armi autonome
+
+R.Brooks realizzava robot con architettura leggera e molto apprendimento
+Roth Pfifer: Robot subsimbolici

+ 1 - 1
Artificial Intelligence/lesson_10.md

@@ -3,7 +3,7 @@
 ###### 4 December 2015
 ###### 4 December 2015
 ## First Order Logic
 ## First Order Logic
 
 
-### Inference prodecures for first order logic
+### Inference procedures for first order logic
 
 
 - __Resolution__
 - __Resolution__
 
 

+ 30 - 0
Artificial Intelligence/lesson_13.md

@@ -0,0 +1,30 @@
+# AI - lesson 13
+#### Francesco Arrigoni
+###### December 2015
+## Planning pt.2
+
+__Planning:__
+- forward planning
+- backward planning
+
+__Sequence__:
+- initial state
+- ACTIONS(g)={relevant and consistent actions for g}
+- RESULT(g,a)=R[g,a]
+- goal test : $g\subseteq s_0$
+- step cost = 1
+
+### Backward Planning
+
+Backward Planning consists in starting from the goal and applying the idea of regression, we are generating other goals.
+
+- __Forward Planning__ is called planning in the *state space*
+
+- __Backward Planning__ is calles planning in the *goal space*,
+
+- Most planners are moving in the *space of plans*.:
+    In this type of planning you start from an empty plan and then explore the state of plans
+
+### Title
+- reactive
+- modeling

+ 130 - 0
Computer Ethics/lesson_01.md

@@ -0,0 +1,130 @@
+# Computer Ethics - lesson 1
+#### Viola Schiaffonati
+###### 19 September 2017
+http://home.dei.polimi.it/schiaffo/CE/
+### Course Introduction
+
+What is Compter Ethics?
+What is Ethics?
+
+#### Ethics
+It's difficult to define, and has many meanings.
+Derives from the Greek word *ethos* that means *custom* or *morals*
+Ethics is the science considering what is **good** and what is **bad**
+Usually good and bad are considered a personal opinion, while here we study this
+matter as a **science**.
+
+Ethics and *morals* is not just an opinion specific to each person, given by
+that person culture; it is possible to study ethics with a **rational** method.
+
+what's the difference between *morality* and *ethics*
+- Ethics is the study of what is good and what is bad
+- Morality is the group of personal opinions and attitudes.
+
+A **dictionary definition** of ethics and morality can point us in a good
+direction but is not enough for a good study of the matter, in general a
+dictionary definition is never enough in phylosophy.
+
+**Aristotle** is an ancient greek philosopher and scientist.
+He did knew of the existence of Physics' laws (maybe not with the same meaning
+of today) but did not give laws for human behaviour.
+
+Aristotle defines ethics using the phrase *in most of the cases* because in
+human behaviour we can see a recurring behaviour but humans may not always
+behave in the same way.
+
+Aristotle's ethics:
+- **Good actions** as the matter of ethics
+- The nature of **human well-being** as its principal concern
+- **Ethical virtues** (justice, courage, temperance...) as central to a
+  well-lived life
+
+This is called **virtue ethics** and was meant as a way to improve an
+individual's life
+
+This cource is intended to improve our *professional life* to improve the design
+and choices we will make during our engineering career.
+
+Ethics reasoning and having in mind ethical problems is required during
+employment in other european countries.
+
+> How is it possible to deal rigorously with ethicsl problems if morality is
+> subjective?
+
+It is useless to stop a discussion by saying "This is my opinion and you have
+yours", 
+
+> discussing about ethics is a process to search the right kind of
+> morality.
+
+> Ethics is the **systematic reflection** on what is moral.
+Morality can still be personal while ethics is a *meta-reflection* on morality.
+
+Ethics is a way to increase our ability to cope with **moral problems**
+But ethics is not a manual with answers, but can give *critical tools*
+
+> what is computer ethics?
+Class responses:
+- moral side of computers
+- autonomy
+- limits
+- how computers change our lives
+- dependency on machines
+- limit between natural and artificial
+- data / privacy (related but general)
+- impacts on human psychology
+
+We will not start by the classical issues of computer ethics, but we will start
+by **enginnering responsibility**
+
+#### Definition
+> Analysis of the nature and social impact of computer technology, and the
+> corresponding formulation and justification of policies for the ethicsl use of
+> such technology (James Moor 1985)
+
+James Moor said that there are *policies vacuums* for example about the debate
+over autonomous cars during malfunction.
+
+#### Classical problems discussed in Computer Ethics
+- **Computers in the workplace**:
+May workers replaced by computers, is one of the oldest problems (like 1970s)
+but it's still actual because today robots/AI can replace humans not only in a
+mechanical way but also in more creative kind of works.
+**Radical alteration** of skills
+
+- **Computer crime**
+It's not the physical security that is in danger, but rather the *logical
+security*
+We will not discuss technical solutions but more general
+political,phylosophical,ethical choices (more than solutions)
+
+Privacy was already a matter before the introduction of computers, but the
+problema has become more radical.
+
+Information society can be seen as **surveillance society** that is a political
+problem more than ethical.
+
+- **Intellectual property**
+There are different aspects of software that we can own:
+    - the source code
+    - the object code
+    - the algorithm
+    - the look and feel
+There are also many ways of *software ownership*.
+For the first time human laws are made on a global context:
+    - Global laws
+    - Gloabl education: and impact on dictatorships, small communities,
+      religions...
+
+#### why Computer Ethics
+> Technology is not neutral
+Technological development is not isolated from the world, but technology is
+always inserted in a social context.
+This idea is called *socio-technical* perspective.
+
+Technological universities usually consider technology a world on its own.
+
+In the design of a product there may be ethical choices, and Computer Ethics may
+help us steer the development of future technologies in a direction that is good
+for humanity (and you).
+

+ 156 - 0
Computer Ethics/lesson_02.md

@@ -0,0 +1,156 @@
+# Computer Ethics - lesson 1
+#### Viola Schiaffonati
+###### 19 September 2017
+### Engineering Responsibility
+
+#### An example: the **Challenger disaster**
+
+In 1986 the first launch of a space shuttle with a civilian onboard,
+the shuttle exploded after 73 seconds from takeoff.
+
+Years later the cause was found to be the O-rings (rubber sealing rings) that
+failed to work properly at low temperatures, so fuel started to leak and caught
+fire.
+
+There is a difference between *legal responsibility* and *moral responsibility*
+
+The **legal resposibility** was attributed to the o-rings failure, and nobody
+was blamed, but the **moral responsibility** is to be found elsewhere.
+
+In July 1985 an engineer at Morton Thiokol (supplier of the O-rings)
+communicated his concernment about the reliability of the O-rings
+
+A project group was set up to investigate the problem but with low funds and
+information, and the research was not successful.
+
+The night before the flight:
+
+The launching had already been delayed 5 times (partly for weather related
+reasong: low temperatures at night)
+
+Morton Thiokol had warned NASA to not go ahead with the launch below 11 degrees
+Celsius.
+
+NASA claimed that *the data were insufficient to declare the launch unsafe*
+
+This is strange because usually we need data to declare something *safe*, not
+the contrary
+
+There was a second conference in which MT decided that the launch had to be done
+(in view of a contract extension)
+
+The points that emerge is that:
+- There is a kind of responsibility from MT in delivering a defective/untested
+  product and making a financial decision.
+- Boisjoly also could have contacted directly NASA about the problem.
+
+After a __Presidential committee__ the blame of the incident was given to a
+communication problem inside NASA and between the suppliers.
+
+The space mission was suspended for 2 years and the communication structure of
+nasa was changed by involving more the engineering part.
+
+Definitions:
+- **accountability** is necessary to be **responsible** of something
+
+For example Boisjoly was not accountable as an engineer, regarding the project,
+but he wa also a *human being* and as such he could have warned NASA for
+example.
+
+- **Responsibility** is linked to the **role** that you have in a situation.
+- Responsibility based on *roles*
+    - **Moral responsibility**
+    - **Professional responsibility**
+- Responsibility:
+    - active responsibility
+    - passive responsibility
+
+#### Passive Responsibility
+
+Is a kind of *backward-looking* responsibility, which
+is relevan after something undesirable occurred.
+- **accountability**
+NASA was accountable to the family of the victims, society and sitting judge.
+- **blameworthiness**
+For someone to be blameworthy, the following conditions are needed:
+- wrong-doing: NASA had to prove the flight to be safe
+- causal contribution: Both NASA project team and Morton Thiokol management
+  could have postponed the launch
+- foreseeability: knowing the consequences of an action
+- freedom of action: NASA team project, MT and Boisjoly were under presure but the
+  pressure was not enough to declare that they lacked freedom of action.
+
+#### Active Responsibility
+
+It's the responsibility *before* something bad happens.
+
+> Prevent the negative effects of technology but also realizing certain positive
+> effects (bovens 1998)
+
+Artifacts can try to implement in their design some values, like "do not drive
+when drunk" or "do not use much water"
+
+Computer engineers have a code provided by ACM
+
+It requires:
+- perception of violations
+- consideration of the consequences
+- Autonomy
+- ...
+
+#### Ideals of engineering
+Are all ideals of engineers morally commendable
+
+ideals may be:
+- Behaving in the profession for the common good and not following pressure.
+- Try to obtain technological advancement / be an efficient engineer
+- Technological enthusiasm
+
+Technological enthisiasm may have consequences, like in the development of
+Google Earth.
+
+negative effect were overlooked, like privacy and security issues.
+One of the boardmen of Google, Marissa Meyer said that "Engineers don't need to
+care about consequences, they are only committed to find the best technical
+solution"
+
+- Effectiveness: extent to which an established goal is achieved
+- Efficiency: the ratio between the goal achieved and the effort required
+consequences
+
+They are apparently neutral, objective and measurable
+example: Taylorism and the idea of scientific management, which attempt to
+design a production process and ultimately society.
+
+Also the **professional practice** of engineers is not morally neutral.
+
+#### Engineers versus managers
+Three models of dealing with this conflict:
+- separatism
+- technocracy
+- whistle-blowing
+
+**Separatism** is the idea that scientist and engineers should apply the
+technical inputs but the management an political organs should make the value
+decisions.
+
+Boisjoly was of this opinion stating that he would have not done anything more
+of what he already did.
+
+**Technocracy** Frederick Taylor proposed that engineers should take over the
+role of managers in the governancce of companies and that of politicians in the
+governance of society.
+
+**Whistle-blowing**
+Renounce to your professional duty and make a sign that something is not
+working, this kind of behaviour is punished by a legal point of view.
+
+#### Collingridge dilemma (Collingridge 1980)
+- It is not possible to predict the consequences of new technologies in the
+  earlier phases
+- Once the negative consequences materialize, it is difficult to change the
+  direction of technological development.
+
+**Constructive Technological Assessment** (CTA) is an approach in which TA-like
+effors are carried out in parallel to technological development.
+

+ 80 - 0
Computer Ethics/lesson_03.md

@@ -0,0 +1,80 @@
+# Computer Ethics - lesson 3
+#### Viola Schiaffonati
+###### 03 October 2017
+### Presentation, papers and more 
+
+To choose the presentation, send an email by 12 october
+
+The topic for the presentation/paper is chosen by the student.
+#### Presentation / paper supervision
+- oct 12
+- nov 9
+- nov 21
+- dec 21
+
+Presentation is 20/30 minutes long, with 5/10 min for Q&A
+It has to be in english
+We can use slides or other support for the presentation (song, dialogue...)
+
+#### Exam dates
+- Jan 31
+- Feb 21
+
+#### Suggestions
+Both paper and presentations must offer an __argument__, we have to support our
+opinion.
+Present reasons for the claims you are making.
+Some originality is required in putting pieces together and develop our own
+ideas.
+
+#### How to choose a topic
+A good paper/presentation makes a __small point__ but makes it clearly and offer
+good reasons.
+
+The paper has to show some __indipendent thinking__
+
+Don't focus on title but on content, *smart titles* are not necessary, chose at
+the end a simple title when the content is already solid.
+
+- The topic must be approved by the instructor, with a provisional title.
+- structure the paper
+- write.
+
+Begin by formulating the __precise thesis__
+- state clearly the thesis in the introduction
+- get to the point quickly and without digression
+- don't try to introduce your argument within a grand historical narrative.
+
+##### Structuring the paper
+
+Define technical or *ambiguous* terms (ex: difference between morality and
+ethics)
+- Think of an imaginary reader that has some knowledge on these topics but is
+  not an expert (ex: colleague of you in this course).
+
+In case of doubts, provide a simple definition, on a footnote.
+
+__Motivate your thesis__, explaining to the reader why he should care about.
+
+Make clear from the beginning the path that i will follow in the argumentation.
+(I will start from this, then discuss on that... and conclude with this)
+
+Explain only the details that are essential
+
+To strenghten an argument it is possible to anticipate and answer objections to
+it
+
+The simple negation of a thesis is not an objection
+
+Bibliography __must be complete__ and __coherent__
+- provide in the bibliography the original reference, even if the resource is
+  found on the web. (Journal, book, issue, number, press institute...)
+
+*Do not* use wikipedia as ultimate source of information on philosophy and
+ethics, instead use __stanford encyclopedia of philosophy__
+plato.stanford.edu
+
+This website has an editor and the articles are written by the most experts in
+the matter (ex: J. van der Hoven)
+
+In case refer to the entry "How to cite this entry"

+ 79 - 0
Computer Ethics/lesson_04.md

@@ -0,0 +1,79 @@
+# Computer Ethics - lesson 4
+#### Viola Schiaffonati
+###### 05 October 2017
+### Values 
+
+#### Intrinsic and instrumental
+- Intristic value: vale in and of itself
+- Instrumental: value because useful for other uses.
+
+Is *privacy* and intrinsic or instrumental value.
+The state of the art is that privacy is an __instrumental value__ to
+indipendence.
+The loss of privacy wound be a threat to our fundamental values.
+
+If a person is being watched by constant surveillance, this determines how the
+person behaves and sees himself.
+
+##### Suggested reading: the circle - Dave Eggers
+
+### Norms
+Norms prescribe what actions are required, permitted or forbidden.
+
+Norms can be seed as tools to realize values
+
+### Virtues
+Virtues are needed to implement Values
+They can be categorized in:
+- moral virtues: justice, honesty, courage
+- intellectual virtues: focus on knowledge and skills
+
+Moral virtues are indispensable in a responsible organization.
+
+### Theories in normative ethics
+__normative relativism__: all moral point of view are equally valid.
+It's a contraddiction in terms:
+> There is no universal norm, but normative relativism is one of it.
+
+__Realism__ states that a reality exists, and is opposed to __skepticism__
+(G.Berkeley, I.Kant, Plato) that doubts the fact that we can experience a real
+world.
+
+> How can i be sure that other people are consciousness?
+
+We have to put a stop to these kind of *skepticism* because otherwise we have to
+negate every form of knowledge.
+
+- Universalism: there is a system of norms that is universally applicable
+- Absolutism: Is a rigid form of universalism in which no exceptions are
+  possible.
+
+We also experiencea gap between __universal values__ and __conflicting norms__
+
+__Utilitarism__: consequences of actions are central to the moral judgement of
+actions (form of *consequentialism*).
+
+Actions are judged by the amount of __pleasure__ and __pain__ they bring about
+(from a society, not an individual perspective)
+
+### Historical roots
+- Jeremy Bentham: focurs on __hedonism__, pleasure is the only thing that is
+  good in itself, and others are instrumental.
+  __moral balance sheet__ in which the costs and benefits are weighted against
+  each others.
+
+- John Stuart Mill: __freedom principle__ (no harm principle): everyone is free
+  to strive for his pleasure as long as you don't deny others pleasure.
+
+### Criticism to utilitarianism:
+- How can you measure happiness objectively
+- Utilitarianism can lead to *exploitation*
+- Consequences may be unpredictable (in particular with technology)
+- ignores the personal relationships
+
+### Duty ethics
+Also known as deontological ethics: action is considered morally right if it is
+in agreement with a certain moral rule, which can be:
+- given by God (bible,koran)
+- Social contract
+- Reasonable arguments

+ 6 - 0
Computer Security/genpdf.sh

@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+
+# Packages needed:
+# pandoc, texlive-core, texlive-latexextra 
+
+cat lesson_*.md | pandoc --latex-engine=xelatex -o course.pdf

+ 93 - 0
Computer Security/lesson_01.md

@@ -0,0 +1,93 @@
+# Computer Security - lesson 1
+#### Stefano Zanero
+###### 10 March 2016
+## What is security?
+Security is usually associated with closeness, locks, contention
+We usually associate it with the image of a bank vault, or a lock.
+
+### CIA paradigm
+- __Confidentiality__
+- __Integrity__
+- __Availability__
+
+For example in a bank withdrawal, the withdraw must always be zero sum (__integrity__), 
+and must occur only when you're at the bank and on your request.
+
+__Availability__ goes in the opposite direction of the previous two concepts,
+because it means diffusing the information instead of restricting it. 
+These conflicting requirements consists in an engineering problem, 
+because we need to find a tradeoff, otherwise the problem would have been simple,
+just requiring to add more locks.
+
+### Vault image example
+By the keypad we can tell that some of the worn out keys are 1 and 9, 
+so the 4-digit code is probably a year. 
+The key concept is that a system may appear secure but there may be 
+something that let us bypass it easily.
+
+### Vulnerability and exploit
+In the case of the lock the vulnerability is the attrition and the fact
+that the mechanical object is not perfect. 
+But the exploit is the way of picking it wit pick and tension wrench
+
+The __vulnerability__ is the problem of a system
+The __exploit__ is a way of using the vulnerability to break the system.
+
+We can know the exploit without knowing the vulnerability
+
+To fix the lock vulnerability we can:
+- Make the exploit harder by putting a pin in the short side making it difficult to pick
+- We can grease the lock by making it closer to the design
+- We can redesign the lock in a way that the vulnerability goes away
+
+### Simple software bug
+The short type has less bytes that the int, so we can assign to int 65536 to short
+it is truncated and becomes 0
+TODO: think of a different exploit for the same vulnerability 
+
+### Security and Protection
+__Security__ is a different thing from __protection level__
+For example a soldier in an ATV vehicle is less secure than a civil in a peaceful country
+In fact security depends on the environments, and on the level of threats.
+The __threat level__ is not always easy to assess, for example the colorado mountain seems safe
+but during the cuban missile crisis it was the most threatened place outside and probably
+safest inside (in the NORAD bunker base). 
+
+### Assets and Threats
+__Assets__ are generally composed of
+- hardware
+- software
+- data
+- __reputation__ is also an important asset
+
+A __threat agent__ is not always intentional, but during this course
+ we focus on *intentional* threats. 
+
+### Attackers and Attacckers
+They are not the same thing.
+The term __hacker__ (in italian *smanettone*, that comes from the italian *manetta* for joystick)
+Whenever we hear a sentence with the word hacker, we can substitute tu *smanettone* and
+check if it still makes sense, otherwise the word hacker has been used incorrectly.
+For example *locksmiths* are able to open locks but they are not thiefs.
+
+Malicious hackers can be attackers, but Attackers are not necessarily hackers.
+Another terminology: __Black hats__ = malicious hackers
+
+The term comes from old western movies in which to distinguish between the good guys and the foes
+the sheriffs were wearing light colored hats while the bandits wore black hats.
+
+### Security as an Engineering Problem
+Some vulnerabilities can not be fixed, and there is no __invulnerable systems__ or
+__secure systems__. 
+`There is no spoon. (Neo)` 
+We cannot design __secure systems__, but we can design systems that are safe enough. 
+We define __risk__ as the combination of:
+- Assets
+- Vulnerability
+- Threats: independent (cannot be changed)
+For example when McDonalds launched in Italy (1996) it used as a marketing strategy the fact of being American.
+But over time they changed their image moving from the USA image to a more local image,
+and this operation changed their threat level because before there were more people pissed off by America
+ that burned flags, threw rocks at the USA embassy and burned down McDonalds. 
+
+

+ 151 - 0
Computer Security/lesson_02.md

@@ -0,0 +1,151 @@
+# Computer Security - lesson 2
+#### Stefano Zanero
+###### 11 March 2016
+## Security as risk management
+In the equation Risk=AssetxVulnerabilities X Threats
+
+We can control only the vulnerabilities, and we need to reduce the risk by
+reducing vulnerabilites.
+There is a __direct cost__ of doing security and it is composed of:
+- Management cost
+- Operational cost
+- Equipment
+
+But the more relevant part are the __indirect costs__
+- Less usability es: a phone with pinlock is more slow than a locked one
+or airport security makes traveling slower.
+- Slower performance
+
+Doing some types of security checks can reduce productivity
+We need to balance these costs with the risk reduction.
+
+Security is not a problem that can be solved by throwing money at it,
+For example adding another layer of metal to the caveau will not
+ make it more secure if the keypad is still broken.
+
+### Airport security example
+Under the airport security *identity checks* are not a security measure,
+because we have not a list of terrorist names and anyway they won't use
+their real name; *identity checks* are only a commercial measure, 
+to avoid ticket reselling.
+
+The *buddy systems*: requiring two different people for doing a particular job
+is used in finance, nuclear weapons or flights cockpit.
+The *positive bag match* is making sure that the luggage is loaded on the plane
+only if the passenger is taking the plane - Backerby disaster
+
+The airlines policies are thought to avoid anything but the suicide attacks
+
+Before 9/11 policies were only considering non suicide hijackers
+After 9/11 the plane is considered as a weapon and the cabin is locked during flight
+And in case of hijacking the pilot has to land the plane somewhere regardless of 
+what happens outside the cabin.
+
+The liquid restriction policy was made after a failed liquid bomb attack,
+it failed because the metal detector avoided carrying a detonator.
+and it was not necessary but it was made because people wanted to know 
+that a countermeasure was taken.
+
+The liquid restraint is still there because it can't be taken away,
+otherwise someone could blame you even if the restraint would have been not effective.
+
+Bad security measures are taken because they fit well in the agenda of people
+taking decisions.
+More things often result in more hassle and in more cost but they do not raise security.
+On the contrary the illusion of security is a security breach itself.
+
+For example lithium batteries are a more serious issue for security but a cellphone ban
+would destroy the business.
+
+### Boundaries
+A __trusted__ element is not a *trustworthy* one but is the one that when compromised,
+breaks the system.
+For example in a computer the CPU is a trusted device because you trust it on making its work.
+So we set a __boundary__ on things you can't control.
+
+A little more paranoia is *helpful*, but in general you need to be secure against the enemy
+that you think you're facing, for example the NSA, your employer, your fiancee.
+
+## Cryptography
+Starting from the greek society writing became more diffused and some
+ systems were created like the strip of sheep skin rounded over a particular stick
+In the following centuries cryptography was more of a wit game (creating/breaking it)
+While during WWII cryptography (and its cracking by Turing) played a key role.
+
+Alan Turing worked at Bletchley Park and created The Bomb, based on poland models
+it was not general purpose but it breaked the Enigma code.
+
+Shannon was also an important subject for Crypto history.
+In 1949 wrote a paper named "Communication theory of secrecy"
+And we are still using the same terminology (plaintext, cyphertext)
+
+Shannon used the Kerckhoffs principle (1883) in his paper and it is the following:
+A cryptographic system is secure only if the attacker can't break it even knowing the algorithm.
+This makes necessary a key to use with the algorithm to avoid the algorithm itself being sufficient to decrypt
+Also we must not be able to derive the key from a plaintext and cyphertext couple.
+
+Shannon wondered if there exists a perfect cipher.
+A perfect cipher should not diffuse information.
+An example of information diffusion is the other players moves in a card game.
+
+__Shannon theorem__
+```
+In a perfect cipher the number of keys must be greater or equal to the number of possible messages
+```
+If we have less keys than messages, i can say that the ciphertext generated by those keys are excluded
+this way we have an information leak.
+
+So perfect cipher exists, the minimal one is called __one time pad__
+__XOR__ is an operation used often in cryptography because it is reversible.
+
+The key used in one time pad is burned when used, and you need to communicate securely a key
+as long as the message, so it is practically unusable.
+
+Practically *no real world cypher is perfect*
+
+### Imperfections and brute force
+The keys can be found by __bruteforcing__ or trying all the possible keys
+until you find an output that makes sense.
+If the key is as long as the message, we can get all the possible cyphertexts that makes sense
+not only the right one.
+
+```
+Any real world algorithm is vulnerable to bruteforce
+```
+
+That is an uneliminable issue
+An algorithm is broken if there is a faster way than bruteforce to break it
+
+### Breaking cyphers
+- __cyphertext attack__ analyst has only ciphertexts with the same given key.
+This attack is the most powerful because we need only cyphertext (less requirements)
+- __known plaintext attack__
+- __chosen plaintext attack__
+
+```
+We don't have a way to know if an algorithm is robust, we can only try to break it and if we succeed we know it wasn't
+```
+In symmetric cryphtography we need to share securely the key, this is an `Elephant in the room` problem, 
+(a problem that is enourmous but nobody speaks about).
+
+It was an issue until in 1976 Diffie and Hellman introduced asymmetric encryption.
+
+exercise: broke the zip example without bruteforcing
+
+### Symmetric encryption
+__Substitution__ also called Caesar cipher, every letter is shifted of the key amount.
+- issues: english have only 26 charachters so we have only 25 keys (bruteforce).
+It is also a monoalphabetic cypher, so repetitions and structured of the words are visible.
+- polyalphabetic way: More secure way of doing it
+__Transposition__ (or diffusion) means swapping the values of given bits
+- For example by writing horizontally in a matrix the charachters of the plaintext 
+and reading vertically the cyphertext
+- It can't be breaked by pen and paper but with a simple python program.
+
+Modern diffusion and substitution algorithms: DES, IDEA, AES
+
+### Case study: DES
+During auditing NSA suggested the adoption of different S-boxes than the originals
+S-Boxes: tables for doing substitutions.
+
+

+ 48 - 0
Computer Security/lesson_03.md

@@ -0,0 +1,48 @@
+# Computer Security - lesson 3
+#### Stefano Zanero
+###### 17 March 2016
+## Note on previous exercize
+__Transposition exercize__
+To solve the symmetric cypher exercize with transposition, we can use 
+the unix tool 'aspell' as an oracle, it will return the syntactically corrected
+version and the number of errors, and we can find the string with the
+minimum number of errors.
+__Zipfile exercize__
+We can look at the magic number (first 4 bytes) to distinguish which file is
+Then i can compare the encrypted header with the standard one and find the 
+key (if it is 4bytes) or the first 4 bytes of the key (if it is longer).
+
+##Keyspace and bruteforcing
+Halving the size of the key we are not halving the number of bruteforce attempts required
+because the number of attempts (or different keys) is exponential to the size of the key (#bits)
+We have to evaluate if the time and the money needed for bruteforcing is worth for the content
+i'm bruteforcing.
+
+##Asymmetric encryption
+It is called *asymmetric* because we use two keys for encryptyng and decrypting respectively
+Contrary to the simmetric example, now the sender uses the public key of the recipient for encrypting
+and its private key for signing.
+__Common asymmetric cyphers__
+- Diffie Hellman, RSA, ECC, DSS
+__Diffie-Hellman exchange__
+Alice and Bob exchange two files.
+The matemathical mechanism is a one-way trapdoor function:
+- It is very easy to compute example a^x
+- It is very difficult knowing y to compute x=loga(x)
+
+We can use the exponentiation to compute the public key Y, but given Y it is practically
+impossible to find X (the secret key)
+In particular
+Pick p prime number, a primitive root of p
+__Primitive root__: a number a such that raising it to any number between 1 and p-1 and computing the modulo p
+we obtain each number between 1 and p-1
+So Alice and Bob chooses a key: number between 1 and P-1 and compute the exponentiation: Ya^Xb mod p 
+
+## RSA Algorithm
+Instead of using the modulo calculus, we can use two large prime numbers
+- Factoring n is exponential to the number of bits of n
+- Computation time for encryptions grows linearly in the number of bits of n (square-and-multiply algorithm in hardware)
+Usually the asymmetric encryption is used to exchange a common secret then a symmetric encryption is used because of performance.
+
+## Hashing function
+

+ 41 - 0
Computer Security/lesson_04.md

@@ -0,0 +1,41 @@
+# Computer Security - lesson 4
+#### Federico Maggi
+###### 31 March 2016
+## Digital Signature
+Collision itself is not very interesting for an attacker, in fact a random email 
+that matches the hash is not useful, an attacker would like to forge a specific
+document and pass an integrity check
+
+### Identity issue
+For real life use we need to associate a name with a key, otherwise we would
+need a secure channel for exchange public keys, otherwise everyone would be 
+able to forge a public key and pretend to be the sender.
+Another instance of the problem is the ability of verifying that the website
+we are connecting to is the real one.
+
+### PKI
+An authority (CA) digitally signs files called __digital certificates__ to bind
+an identity to a public key. es: X.509 is a format for pk certificates.
+A certificate contains informations in the identity and the public key and is 
+signed (hashed and encrypted) by the CA.
+This introduces a problem of __trust__, who trusts the CA?
+We need a __Top-level CA__ (root CA, source CA), that uses a self-signed certificate
+to say "I am myself"
+Then we can make a chain, or rather a tree of CA trust, where the trusted element is the root CA
+
+#### How to distribute the trusted element?
+A way of *decentralizing trust* is the __web of trust__
+There is a whole research field about "What you see is what you sign"
+
+### Identification vs Authentication
+- Humans mutually authenticates implicitly, eg: by recognize the face, ecc...
+- Human to computer authentication is not easy
+- Computer to computer authentication is easy
+
+#### Three factors of authentication
+- Something that you know: password, pin, secret handshake
+- Something that you have: Door key, smart card, token
+- Something that you are: Face, voice, fingerprints.
+
+Usually some of the three measures are combined, example: two factor authentication
+

+ 47 - 0
Computer Security/lesson_05.md

@@ -0,0 +1,47 @@
+# Computer Security - lesson 5
+#### Federico Maggi
+###### 1 April 2016
+## Authentication
+__Authentication__ solve the problem of *validating* and identity.
+Can be
+- unidirectional
+- bidirectional (mutual): both entities authenticates
+Authentication is necessary for authorization: enforcing of certain permits or not.
+
+## The "to know" factor authentication
+Passwords or secrets
+can be stolen or guessed, or spied, or even bruteforced.
+We can mitigate these problems with enforcing change of password or lenght constraints.
+Website with hints on strong passwords.
+`passfault.appspot.com`
+
+### Problem of sending a secret over untrusted channel
+for example over the internet it is not safe to send the secret in plaintext for authentication
+A more safe system is the __challenge response__ one, for example the server asks you
+to send him to compute the hash of *some random data + your secret*
+This consists in a cryptographic proof that the user owns the password.
+A typical response is Hash(random data + secret + other random data) + other random data.
+Usually in this case *mutual authentication* is needed to avoid __Man in the middle__ attacks.
+__Replay attacks__ consists in intercepting the password and using it again.
+
+### Secret storage
+The passwords must be never stored in *cleartext*, instead the *password hash* can be stored.
+Sites that emails back you your password in cleartext, it is an implicit proof that
+they store your password in cleartext.
+
+Also __password recovery__ procedures must be implemented carefully otherwise they can be
+a way of circumventing the main security measures.
+
+## The "to have" factor
+There is a difference between *telling* a colleague a secret and *giving* a physical
+object that contains a secret (e.g. a smart card with your photo on it)
+Up to now they are cheap and offer a good level of security for the reason above.
+
+`Financial Crypto 2016 - How google killed 2factor authentication`
+
+## The "to be" factor
+Financial Crypto 2016 - How google killed 2factor authentication
+
+## Single Sign On
+Google, Yahoo, Facebook can be used as identity providers.
+

+ 44 - 0
Computer Security/lesson_06.md

@@ -0,0 +1,44 @@
+# Computer Security - lesson 6
+#### Federico Maggi
+###### 7 April 2016
+## Software Security
+
+There is nothing really __secure__, there is something __secure enough__.
+__Software security__ is a problem of design, but designing a software
+in a secure way is __very hard__.
+An unmet specification about security is a __security issue__.
+
+## Disclosure
+Until the end of 1990' software vulnerabilities were not disclosed,
+instead they were traded between security experts or they were sold.
+At one point people began using __full disclosure__ to press software
+vendors to fix vulnerabilities, that consists in making public information
+about the vulnerabilities so that the vendors were forced to fix it
+before someone takes advantage of it.
+
+## Anti Disclosure
+After the full disclosure movement vendors realizes that offering visibility
+to people disclosing bugs was a way of making them work for you instead of
+against you, But then a new movement rose: the __Anti full disclosure__
+that states that after the peoples gained visibility they have no
+more reasons of giving vulnerabilities for free.
+And this made the security expert role a paid job.
+
+The last developement in the sector was the introduction of __bug bounties__
+
+## Principles of secure design
+- KISS
+- Discard privileges as soon as possible
+- Open design
+- Concurrency and race conditions: __race conditions__ is an entire category of issues.
+
+## Key Issues of secure design
+- fail-safe and default deny: programs should __fail-close__ and not fail-open
+- use of shared-resources or untrusted libraries
+- filter the input and outputs
+- don't write crypto code, use tested libraries.
+
+## Conclusion
+Volnerabilities may be __dense__ so taking out one vulnerability does not make the software
+more secure.
+

+ 78 - 0
Computer Security/lesson_07.md

@@ -0,0 +1,78 @@
+# Computer Security - lesson 7
+#### Stefano Zanero
+###### 14 April 2016
+## ASM function call
+ESP and EBP registers delimit the current location of the stack,
+they point to the *frame of activation*
+The `call` intruction saves the current EIP on the stack,
+The equivalent instructions to `call 0x8048484 <foo>` are:
+```
+push %eip
+jmp 0x8048484 ~foo()
+```
+The difference with the sole call of `jmp` is that the call saves
+the current state of EIP to return to it later.
+After the jump the stack allocation is done:
+- Save the EBP on the stack
+- Set the net EBP to current ESP
+- Allocate space on the stack incrementing ESP
+```
+push %ebp
+mov %esp, %ebp
+sub %0x4, %esp
+```
+To view this result I should disable the optimization with `-O0`
+and `-preferred-stack-boundary=2` turning off some optimization
+that store multiple (short) variables per stack word.
+Before the function return, the return value is moved into EAX
+The return from function is made with the `leave` op
+```
+mov %ebp, %esp
+pop %ebp
+ret
+```
+That deallocates the current stack, and the `ret` op pops the last value
+on the stack to EIP to restore it.
+
+## Stack Smashing
+Suggested reading: `Smashing the stack for fun and profit`
+This works in C because it doesn't do memory management for you
+like Python or Java
+If we have a code like this
+```
+char buf[8];
+gets(buf);
+```
+And we input during execution a sequence longer than 8
+we get a *segmentation fault*
+That is actually raised by the `jmp` op trying to jump to 
+a meaningless position in memory, since we overwritten EIP
+that was stored on the stack, by growing the heap.
+Maybe it would have been enough to overwrite the return value 
+wothout overwriting EBP and EIP, and that is another
+security vulnerability itself.
+
+To jump to any function i would need to setup the parameters correctly
+on the stack.
+I can also jump into a function of a library loaded into memory
+This is called __return to library__ or in particular __return to libc__.
+Also the environment variable loaded with a program are stored on
+top of the stack always in the same place, so i can put code in there
+and jump to it.
+Requirement for stack smashing:
+- The size of the buffer is not checked
+- Overflowed buffer has enough room for code
+Also we need to know at what address the stack is
+
+### Get the address of the stack
+We can use a debugger to stop the execution before the vulnerability
+and get the address of memory where ESP is stored
+On our own machine i can use a code to print to screen the position of ESP 
+(see slides)
+The debugger method is not so reliable because some debuggers like gdb add
+an offset to allocated memory.
+We can reduce the need of precision filling the heap area with `nop`
+forming a *nop sled* that make the processor go through to the right exploit code.
+This is a measure to make the exploit work reliably on remote machines,
+ans this is part of __weaponizing__ an explloit
+

+ 62 - 0
Computer Security/lesson_08.md

@@ -0,0 +1,62 @@
+# Computer Security - lesson 8
+#### Stefano Zanero
+###### 15 April 2016
+## Stack smashing pt. 2
+We have now established that we can jump (modifying EIP) to any point in memory.
+We may want to jump to a function in our program, or a function in a library
+included in our program.
+For jumping inside a function we will need to prepare the parameters
+on the stack for the function to execute properly.
+```
+unsigned long get_sp(void) {
+   __asm__("movl %esp,%eax");
+} // content of %eax is returned
+
+void main() {
+   printf("0x%x\n", get_sp());
+}
+```
+With this code we can have the ESP of the get_sp function that will 
+be similar to the main one,
+In general __it is difficult__ to get the actual value of ESP,
+but we can make a good guess about it.
+The __NOPsled__ technique can help if we do not know precisely where our code 
+will be placed
+
+### What to execute now?
+The hystorical objectiva was to spawn a privileged shell
+runnign a so called __shellcode__
+In linux we could use a command like `execve`
+For launching the needed system call we need to fire an interrupt.
+ex: we use an `int` op with code `0x80`
+The parameters we will need to pass to `execve` are the following:
+- First parameter: "/bin/sh"
+- Second parameter: NULL, represent environment variables.
+
+If we disassemble the function `__execve` we know that
+the function pass the parameters through the registers and then
+calls `int 0x80`
+```
+movl $0xb,%eax
+movl 0x8(%ebp),%ebx
+movl 0xc(%ebp),%ecx
+movl 0x10(%ebp),%edx
+int  $0x80
+```
+Then we could use this code for our shellcode
+The problem is that we need to have the address of the string for `argv[0]`
+to pass it as parameter.
+But now we have already the possibility of running code, 
+so we can get the machine will in the address on its own.
+The trick used is *jump and call*
+For which we use the `jmp` op with the offset to `call` function
+the call function jumps again to the second instruction (pop)
+Then we pop the ADDRESS from stack to ESI register,
+then we have the ADDRESS to use to build the parameters for the `execve`
+
+The 0 bytes in the assembly code create problems with screen operations,
+to avoid this we can use the `jmp short` instruction instead of `jmp`
+The problem with 0 is that since we use C string functions to manipulate
+our exploit code, the function may terminate the string when they find 
+a NULL byte (0x00 or /0), that usually terminates strings.
+

+ 43 - 0
Computer Security/lesson_09.md

@@ -0,0 +1,43 @@
+# Computer Security - lesson 9
+#### Stefano Zanero
+###### 21 April 2016
+## Preparing the Memory
+To effectively use the buffer overflow we need to create the exploit buffer
+and put it in memory using a helper program, the exploit buffer will include
+half size of nops, and following the shellcode and the ESP.
+
+We may want to have more than one repetition of the ESP because if the program
+we are attacking is distributed already compiled, we can be precise
+but if it has been compiled ad-hoc, then it may have offsets.
+A clever script prepares the buffer and loads it into an environment variable `EGG`
+before starting a terminal, then i can `./executable < `echo $EGG` and pass the buffer
+that i couldn't have written by keyboard.
+We can make a more effective shellcode making it tinier, with the same techniques 
+that were used in the demo-scene.
+We can alternatively use the saved EIP of a function pointer if that function is accessible
+by our buffer and run before the exploit.
+One of the most common programming error is the *off-by-one* made by counting arrays
+starting from 1 instead of 0.
+
+## Defense from buffer overflows
+The main cause are programming errors
+### Source code level defense
+- Use safer librearies, es: `strncopy` checks for input size.
+### Compiler level defenses
+- Compilers can notify about source code mistakes
+- Randomly allocation of variables on the stack
+- Use of a canary that is a sacrificable piece of code, that
+is checked to make sure the buffer was not exploited
+(Reference from canaries used by miners)
+Static canaries can be easily replaced, there are
+more effective tecniques like __Terminator canaries__ (made of `\0`)
+and __Random canaries__
+If we seek performance we may disable canaries by NOT using `-fstack-protector`
+Buf for normal programs it should stay enabled.
+
+- Operating System level:
+    - Non executable stack, e.g. NX bit that make the program crash if jump into a section of memory with NX enabled
+    - Address Layout Randomization; for example in linux the stack is shifted in a 2MB range every execution.
+
+## Format String Bugs
+

+ 49 - 0
Computer Security/lesson_10.md

@@ -0,0 +1,49 @@
+# Computer Security - lesson 10
+#### Stefano Zanero
+###### 5 May 2016
+## Format String Bugs
+The format string bugs are typical of C language but the idea
+can be applied also to other languages.
+The key part of a string formatting function is the *format string*
+The first parameter of the f.s.f. is Interpreted as the format string
+So whatever i pass to the function, the function use it.
+In the format string there are placeholders that tell the function
+how many more parameters there are, and the function is going
+to look for those on the stack.
+
+So we can access arbitrary data on stack, so we can:
+- Bypass __ASLR__ by knowing the stack allocation address
+
+It would be interesting if we would be able to write on the stack.
+There is the `%n` placeholder that is used to write on a variable
+the number of characters currently written.
+This was used to count characters to create command line interface
+on fixed terminals, but it's not used anymore.
+
+At some point in the stack we will find the same variable we passed
+to the format string function.
+
+Our current limit is that we can pass only a 256 charachter string to
+the format string variable, but hopefully the format string function
+acceps `%N$x` as a placeholder, that tells the program to fetch
+the Nth parameters, that even if it doesn't exist, it corresponds
+to some value on the stack.
+
+As of now i can only write the number of characters currently printed,
+but i would like to write in memory an arbitrary number.
+The trick is to use `%Nc` that padds the printed number with N figures.
+The number accepted is a short int (16bits,64K max value)
+But i can still write 32bit values by using two `%c` and writing first the
+number with the lower value and then the number with the higher value
+(Using another %c).
+
+What i need for the complete exploit is:
+```
+"<addr1>[4bytes]<addr2>%x%x%x%x%c%n%c%n"
+```
+I will need to tune the `%c` parameter based on the actual lenght of the string 
+and the target value (length) that we want to write in memory.
+
+The simple `%n` overflows and writes always 4bytes word, to write
+16 bits at a time we can use `%hn`
+

+ 27 - 0
Computer Security/lesson_11.md

@@ -0,0 +1,27 @@
+# Computer Security - lesson 11
+#### Stefano Zanero
+###### 6 May 2016
+## Web Application Security
+The typical target of web attacks are the browser of the users
+and the data on the server.
+It is the current trend to offer software not anymore as clients
+but as web applications, this is true for SaaS and Corporate Intranets.
+
+The core of navigation is going through pages carrying over a state
+But that's an illusion in HTTP pages because it is intrinsecally stateless.
+So we're building __stateful__ interaction over HTTP that is __stateless__
+Also HTTP doesn't support __authentication__ by itself, so it is 
+implemented in the application.
+
+> People make mistakes.
+And the fact that web applications have the view side not under the
+control of the programmer, in fact it runs inside the browser
+
+__SOP__ is a common policy adopted by browsers and consists of allowing scripts
+coming from a website to access only data from that website.
+
+__XSS__ or __cross site scripting__ is the technique of putting in a textbox
+a javascript executable code marked as `<SCRIPT>` that will be executed in
+the client and violate the __SOP__ policy to access data or perform operations
+on the attached site from the client.
+

+ 18 - 0
Computer Security/lesson_12.md

@@ -0,0 +1,18 @@
+# Computer Security - lesson 12
+#### Stefano Zanero
+###### 6 May 2016
+## Web Security pt.2
+To protect a website from scripting in the comments section
+A good solution is to whitelist characters that can't make 
+a javascript script.
+
+Our other option is to __escape stuff__, that is
+to escape dangerous characters we can substitute the nonterminals
+to the corresponding character
+For example replace > and < with &gt &lt
+or replace & with &amp;
+
+__CSP__ or Content Security Policy is a generalized version of __SOP__
+
+## SQL INJECTION
+

+ 103 - 0
Computer Security/lesson_13.md

@@ -0,0 +1,103 @@
+# Computer Security - lesson 13
+#### Stefano Zanero
+###### 19 May 2016
+## Web Security pt.3
+The debug messages of dbms when left enabled are very useful to an attacker
+Because this *information disclosure* brings a lot of useful data.
+
+### URL Parameter Tampering
+Consist in changing the parameter encoded in the URL,
+but that is not the problem itself, the problem is that whether
+i change that value, the site should not allow me to see other pages.
+Example: changing patient id and seeing the page of another patient.
+
+If the user is already logged in, it doesn't make sense to specify its id on the URL.
+Also if the parameter is used for a SQL query, i can make a SQL injection.
+
+Another example would be appending 
+```
+%2f..%2f..%2f..%2fetc/passwd
+```
+If the webserver has a vulnerability I could be able to read an arbitrary file on disk.
+
+### Password management
+It is really important not to store the passwords in clear on the server,
+but even if someone stole a list with hashes of the password.
+The attacker could compare the list to a precomputed list of hashes, 
+and do a sort of *bruteforce* attack but with the work done offline and before time.
+
+A common trick to avoid this is __salting__, and consists as a hashing the password
+together with a number used only once (called nonce in crypto)
+
+Another good measure is using *slower* hashing function, so that bruteforcing
+becomes harder.
+
+In summary normal people:
+- use always the same password
+- or use a different one every time and use the reset password procedure
+
+The __reset password procedure__ is itself an alternative autenthication measure.
+this procedure use a reset link which can be used only once, and this way it is
+*tamper evident*, so i know if it has been compromised.
+
+Another way is to send an email to the register address whenever an important information
+is changed in the account, so at least we know.
+
+The __weak point__ of this procedure is the email account, 
+if someone breaks through the email account you use for registering,
+it can reset the passwords of your social networks and other.
+
+If the compromised account is the one of a trade journalist,
+and a fake tweet is made about a great trade operation.
+
+This can cause great consequences, because people will trade
+according to the news, sometmes even if it's not confirmed
+And so it becomes a __self realizing prophecy__
+
+Or for example a video shared by an important sport athlete would 
+be spread very fast.
+
+Why do sites use __security questions__?
+they are not meant to authenticate the user but to prevent
+An unlimited number of reset requests, making a denial of service.
+
+Regarding __account locking__
+it can be target of *reverse bruteforcing* such as trying the most used passwords on
+all the different accounts of the website.
+
+Locking the accounts turns the problem of bruteforcing into a possibility
+of denial of service, because if someone runs a bruteforse everytime the
+lock expires, i would not be able to access the account anymore.
+
+A good way to avoid this is to use non enumerable user names.
+Blocking IP address is a good approach but it can block entire
+group of users that use the same IP behind NAT.
+
+Adding an exponentially increasing delay for a specific IP address is another good measure.
+
+We can also use a captcha to avoid widespread use of scripting.
+
+### Cookies
+
+Were meant initially for user customization of websites, a lot of years ago.
+They are a code  that allows the site to recognize you whenever you connect again.
+
+The nasty side of this is when they are used by advertisement and tracking websites.
+They are a code  that allows the site to recognize you whenever you connect again.
+
+The nasty side of this is when they are used by advertisement and tracking websites.
+And if a cookie is stolen, it is as valuable as username and password.
+
+### Multiple sessions
+To create __multiple sessions__ *unique identifiers* are used.
+Often the websites are using a session from which you can never log out
+and every time you visit the website, you are presented the last page you were the last time.
+This is done to gather the greatest data possible, because that's their business.
+
+Facebook sells data so the app is the most streamlined possible, and creation
+of events or so is easy, because all these things brings money to facebook.
+
+## Recap on web security
+The essence of the problem is that using web technology 
+we need to mix code(e.g. HTML) and data (e.g. the blog comment)
+

+ 23 - 0
Computer Security/lesson_14.md

@@ -0,0 +1,23 @@
+# Computer Security - lesson 14
+#### Stefano Zanero
+###### 20 May 2016
+## Network protocol attacks
+The three common types of attacks are:
+- Denial of Service: service unable to serve users
+- Sniffing
+- Spoofing
+
+### Denial of Service
+A __Killer packet__ is capable of bringing down the machine which is sent to.
+Ping-o-death(ICMP) and Teardrop(TCP) Were two vulnerabilities with
+the same principle of just handling cases provided by the standard,
+and not handling abnormal or erroneous packets.
+
+Attacks like __smurf__ are hardly fixed because the ones that have interest
+of fixing the vulnerability are not the same ones that need to spend
+the money in order to fix it.
+
+### Sniffing
+Switched networks as opposed to hub-based networks send to every host
+only the packets that are destined to it, and also are faster.
+

+ 14 - 0
Computer Security/lesson_15.md

@@ -0,0 +1,14 @@
+# Computer Security - lesson 15
+#### Stefano Zanero
+###### 26 May 2016
+## IP Address Spoofing
+The fact that IP addresses can be spoofed is a fact due to the design of the IP protocol
+But not necessarily is going to be a vulnerability,
+if for example on the application level i question the truthfullness of the sender
+address, it is not a problem anymore.
+
+The simple TCP three way handshake, having randomizing SEQ numbers, offer
+a protection against IP spoofing, in fact if the attacker does not get the
+SYN+ACK packet, he cannot begin a connection.
+
+

+ 44 - 0
Computer Security/lesson_16.md

@@ -0,0 +1,44 @@
+# Computer Security - lesson 16
+#### Federico Maggi
+###### 9 June 2016
+# Network Security / SSL
+
+__exercize__: Try to write the firewall rules for a DMZ multizone architecture
+
+## VPN Networks
+A VPN can act in two modes:
+- Full tunnelling: all the traffic of the client is tunnelled through the VPN
+- Split tunnelling: only the connections towards the corporate network are routed through the VPN.
+
+The full tunnelling wastes more bandwidth but instead the split tunnelling creates a bridge 
+between an unprotected network and a protected one.
+
+# Exam Preparation
+
+__Ex. 1__ True or False statements
+- RSA 2048 is more robust to bruteforcing than 256 AES
+False, we can not compare directly an asymmetric RSA and symmetric AES
+
+- No encryption algorithm is perfect, as they are all vulnerable to bruteforcing
+False, because OneTimePad is invulnerable to bruteforcing because every cyphertext decrypts to every possible plaintext
+
+- An encryption algorithm is broken if there is a way to get the secret by using the cyphertext
+False, an algorithm is broken if there is an attack significantly faster than bruteforcing.
+
+__Ex. 2__
+To avoid Buffer overflow we can
+- Use a secured version of the `gets()` like `read()` specifying number of bytes to read
+- Use a `for` cycle to read char by char
+- Use a `scanf()` specifying %15c
+
+__Ex.3__
+Assuning IA-32, why must we split the content to be written in the target cell in 2, 2-bytes chunks?
+Because %c allows to print up to 64K chars (16bits)
+
+The printf is vulnerable only in the case that the format string is variable and can be used to write
+an exploit, if it is fixed in the source code, it cannot be exploited.
+
+__Ex.4__ on SQL injections
+
+__Ex.5__ ICMP Smurf attack
+

+ 44 - 0
Computer Security/lesson_17.md

@@ -0,0 +1,44 @@
+# Computer Security - lesson 17
+#### Stefano Zanero
+###### 16 June 2016
+
+# SSL Security
+
+## New protocol adoption
+Every time a new protocol needs to be adopted, it is a critical problem the critical mass question.
+This can be a major problem for startups/business plans that aim to replace a big player
+with a new, better system.
+
+## SSL
+__Phases__:
+- cipher suite + random data
+- certificate verification
+- pre-master key exchange
+- pre-master key encryption (and optional signing)
+
+The signing of the master key by the user authenticates it but it is an optional feature
+and nobody uses it (99%) so the majority of the times the client is not authenticated.
+
+The exchange of random data in SSL is used to ensure __freshness__ of the communication,
+that is used to avoid __replay attacks__ in which a malicious server replays the
+exact messages of an old communication and establishes a connection.
+
+### Man in the middle
+A simple man in the middle attack can't get the content of a connection because it doesn't 
+know the server private key.
+
+## SET system
+Meant to protect __transactions__ not __connections__
+
+SET story was used by VISA and MasterCard to give the resposibility of transaction frauds
+entirely to merchants, because they offered a secure alternative but the merchants
+decided it was not economically convenient to adopt.
+
+# Malware
+
+Categories:
+- Virus: is not an executable but a piece of code able to infect programs and self propagate
+- Worm: is an executable for of virus
+- Trojan Horse: Is a program that seems useful or innocent but hides malicious behaviour
+like creation of remote access.
+

+ 32 - 0
Computer Security/lesson_18.md

@@ -0,0 +1,32 @@
+# Computer Security - lesson 18
+#### Stefano Zanero
+###### 17 June 2016
+
+# Viruses
+Look for ted talk history and viruses.
+
+From 2004 on the production of worms stopped because the people that
+were developing worms put themselves in business and began creating
+ransomware, scareware and state-sponsored malware.
+
+__Ransomware__ is a form of getting money from malware.
+
+Most computer viruses are not harmful because a virus that takes
+down the host as soon as it's infected, cannon propagate.
+For example cold infection is a lot more effective than ebola
+because it does not kill you and let you propagate it.
+
+Before the introduction of macro viruses, people were trained
+on the fact that office documents were harmless and could
+be opened safely, but after introduction of macro language
+in office, macro viruses began to spread.
+
+TCP connection are latency bound, so the more is loaded one of the host,
+the slower the connection will be.
+So TCP based viruses like code-red were slowing down themselves.
+But UDP based viruses like SQL hammer are much more effective.
+
+SQL hammer was based on the assumption that there were databases exposed on
+the internet while they didn't have any reason to be.
+
+

+ 32 - 0
Computer Security/lesson_19.md

@@ -0,0 +1,32 @@
+# Computer Security - lesson 19
+#### Stefano Zanero
+###### 23 June 2016
+# Antivirus and Anti-malware
+
+Commercial products for antivirus employ __signature based detection__ or __heuristics__
+but they never apply __behavioral detection__ that is limited to the research field.
+This is basically because commercial products are focused on __detecting__ malware
+and not __analyzing__ its behaviour.
+
+## Viruses and Worm stealth techniques.
+
+- __Polimorphism__ is when the virus changes its shape with every infection,
+for example encrypting the malicious payload every time with a different key.
+The problem in this case for analyzers is that often signatures recognize
+the dectyptor code and not the malicious code, so one signature mathes 100s viruses.
+
+- __Packing__ is used by malware to encrypt the code but also used my DRM software.
+
+# Rootkits
+The word __rootkit__ originally meant the set of software to gain root access and 
+maintain it on a machine.
+
+__Userland__ rootkits would require trojanize lots of utilities that otherwise could
+be used to detect the attack, like `ls, du, netstat...`
+
+It is much simpler but more difficult to have a __kernel__ exploit.
+
+For computers it is a very important issue the __supply chain__, or the fact that
+you cannot ensure that the vendors of all the components of your computer 
+or the oem vendor haven't compromised your device.
+

+ 24 - 0
Computer Security/x86_lesson.md

@@ -0,0 +1,24 @@
+```
+eax = 2     esp=FFF8
+ebx = 44
+
+push eax
+push ebx
+
+FFFF8
+FFFFC 44
+FFFFF 2
+```
+
+### Push instruction
+```
+mov [esp], eax
+sub esp, 4
+```
+### Pop instruction
+```
+add esp, 4
+mov eax, [esp]
+```
+
+

+ 172 - 0
Cryptography/exe_01.md

@@ -0,0 +1,172 @@
+
+If the frequency graph has the same shape of the english language,
+it is a permutation cipher, if the shape is the same but labels are different, 
+it is a substitution cipher, or a combination of the two.
+
+The permutation cipher does not affects the frequency graph because the analisys
+is done on the text as a whole which ignores the scrambling.
+
+Growing the keylenght in a vigenere cipher, i expect to see the frequency curve
+flattening, until it become completely flat when the key is long as the text
+(one time pad)
+
+To have a bigram that remains from the plaintext to the cyphertext, the
+beginning of the n-grams should be aligned with the key.
+
+If in a vigenere cipher we have the frequencies 6, 24, 30
+the key lenght candidates are 3, 6, 2,1. We start loogin from the longest key.
+
+If the vigenere is using a key lenght of 3 and i pick 6, i will still find a key
+with is a double repetition of 3 lenght key.
+
+### SMS example
+If i'm encrypting sms messages (160bytes) with a 256B key:
+- if I use every time a different key, the cipher is not breakable because is
+  akin to a onetimepad.
+- if I use always the same key I will be using actually 160bytes of the key, so
+  it's a matter of collecting enough ciphertexts and concatenating them to run a
+  classic vigenere breaking
+
+__Unicity distance__:
+Even if we are using bruteforce, if we have less that the unicity distance in
+ciphertext, i will be unable to tell apart the actual plaintext from a group of
+texts that pass the test.
+
+Defined as: $n_0 = {log_2{|k|}/{R_L * log2{|M|}}$
+
+Redundancy $R_L = 1 - {H_L}/{log_2{|M|}}$
+
+Entropy of english $H(M) \le 1.5b$
+
+- Best case, 
+the message has an extremely redundant message, 
+
+High redundancy what dinstinguishes english from random data.
+
+With more redundancy is is more difficult to distinguish a meaningful message
+from one that it isn't.
+
+Entropy of a random (lowercase) letter $H(rnd letter) = -\Sum{s}p_s * log(p_s)$
+$- (26*1/26 * log(1/26)) = log_2(26)$
+$$log_2(16) < log_2(26) < log_2(32)$$
+
+So using lowercase letters as key I have an entropy of 160b, between 640 and
+800.
+
+$$n_0 = \frac{log_2(|K|)}{R_L * log|M|}$$
+$$n_0 = \frac{800)}{0.75 * 4.7}$$
+$$n_0 = \frac{800}{3.5}$$
+$$n_0 = 200$$
+
+I need at least 2KB of text to at least get a unique plaintext when doing
+bruteforce.
+
+__Honey encryption__
+Takes a meaningful plaintext and a source of random number, and outputs a 
+uniform distribution of characters, which even when bruteforcing decrypts to a
+bunch of random numbers.
+This encryption scheme is used in credit cards to avoid the risk of bruteforce
+attacks.
+
+__Playfair cipher__
+- Start with a 5x5 grid
+- Fill with keyword, avoiding letters already present
+- Fill with english alphabet, still avoiding repetitions.
+ W | I | N | T | E
+---|---|---|---|---
+ R | M | U | A | B
+ C | D | F | G | H
+ K | L | O | P | Q
+ S | V | X | Y | Z
+
+ I take the plaintext *crypto*
+Take two letter and replace them with their neighbors
+>>> Missing encryption procedure
+
+ The keyspace is $25!$ because it is a still a permutation of the english 
+ letters even if it is folded.
+
+$$ln(n!) = nln(n) - n + O(ln(n))$$
+Shorthand formula
+$$n! = e^(nlog(n)) - e^n + e^log(n)$$
+
+$$25! -> 25*4 ~= s^120$$
+
+Bruteforce reference
+Powers of two:
+- 0-40 laptop
+- 40-50 GPU
+- 50-60 bunch of GPUs
+- 60-70 calculus center
+- more than 80 unlikely
+- 100 the energy obtained burning all the oil is not sufficient.
+
+The table rule is encrypting a digram into a given digram, so I can use a large
+lookup table to compare the digrams.
+
+__Nihilist cipher__
+A variation of the playfair cipher used by the U.S. war prisoners,
+Has two keys:
+- k1: build the polybius square
+- k2: run it through the table
+ * for example "chair" look it up in the square and report the coordinates
+ 31-33-24-12-21
+
+Procedure
+- Run the plaintext through the table
+PTX= "Test"
+14-15-51-14
+- Add the key (non modular) to the plaintext
++ 31-35-24-12
+45-50-75-26
+
+Is the thing breakable? what is the keyspace? can i run a bruteforce?
+The two keys are independent so I will need to bruteforce both of them.
+__Keyspace__
+The second key will be the entropy of a symbol times the number of symbols
+The keyspace of the first key is 25! as before
+
+The first encoding can be seen as a funny substitution cipher
+Also there's a bias in the number, it is more frequent to find higher numbers,
+I can compare the distribution of cyphertext histogram to the plain english one.
+
+In the playfair cipher, a letter can be never envrypted as itself.
+
+__Enigma__
+The enigma machine had three cogs that applied three substitutions and again in
+reverse order thanks to a reflector.
+A peculirarity was that the signal of a letter could never be sent back to the
+same letter because it would cause a short circuit.
+
+The only position that mattered was the first one because the remaining
+positions were obtained by rotating the rotors.
+The commercial version of enigma has three rotors, or 26³ keyspace,
+While an enhanced version has three rotors to be picked out of 5
+thus getting a 26³*5*4*3
+The plugboard added a 26*24*23...*15
+This is more than was done by the rotors alone, and a version with 10 cables was
+introduced by just adding more cables.
+
+A contradiction is when a single ciphertext letter gets mapped to wto different
+letters, with can't be done in a single wiring machine.
+The military version had a plugboard with 26 sockets and 6 cables.
+
+6 face die
+3 random variables
+- x = {1...6}
+- y = {odd, even}
+- z = {result<=3, result>3}
+
+Compute the entropy of these guys and at least the joint entropy of (x,y), (z,y)
+H(x) = -6*1/6*log2(1/6i)= log2(6)
+Rolling a dice gives 2.6b of entropy
+H(y) and H(z) gives 1bit of entropy, the dice become equivalent to a coin
+
+H(xy) 
+We make the table of the thwo wariable, so the joint entropy of XY is as Y,
+because there is a correlation
+
+H(zy) gives a different correlation
+
+
+

+ 12 - 0
Cryptography/lesson_01.md

@@ -0,0 +1,12 @@
+# Cryptography
+#### Gerardo Pelosi
+###### 6 March 2017
+
+---
+
+## Introduction to Cryptography
+Encrypting is different from encoding:
+- encoding is meant to protect the information from errors
+- encryption is meant to protect the comunication content
+
+

+ 8 - 4
Formal Languages and Compilers/lesson_03.md

@@ -69,8 +69,8 @@ $$ e_N = (a_1\cup (b_2b_3))^*(c_4^+ \cup (a_5 \cup (b_6b_7)))$$
 3. Isolate the subexpressions and put them into evidence
 3. Isolate the subexpressions and put them into evidence
 $$ (a_1\cup (b_2b_3))^*\;\;\;\;c_4^+ \cup (a_5 \cup (b_6b_7))$$
 $$ (a_1\cup (b_2b_3))^*\;\;\;\;c_4^+ \cup (a_5 \cup (b_6b_7))$$
 $$ a_1\cup (b_2b_3)\;\;\;\;\;\;c_4^+\;\;\;\;a_5 \cup (b_6b_7)$$
 $$ a_1\cup (b_2b_3)\;\;\;\;\;\;c_4^+\;\;\;\;a_5 \cup (b_6b_7)$$
-$$ a_1\;\;\;\;b_2b_3\;\;\;\;\;\;c_4^\;\;\;\;a_5 \;\;(b_6b_7)$$
-$$ a_1\;\;\;\;b_2\;\;\;b_3\;\;\;\;\;\;c_4^\;\;\;\;a_5 \;\;\;b_6\;\;\;b_7$$
+$$ a_1\;\;\;\;b_2\;\;b_3\;\;\;\;\;\;c_4^+\;\;\;\;a_5 \;\;(b_6b_7)$$
+$$ a_1\;\;\;\;b_2\;\;\;b_3\;\;\;\;\;\;c_4^+\;\;\;\;a_5 \;\;\;b_6\;\;\;b_7$$
 <!--*-->
 <!--*-->
 
 
 ### Different parenthesization
 ### Different parenthesization
@@ -89,8 +89,8 @@ If the two regexp $e'$ and $e''$ can be factored as
 $$e'=\alpha\beta\gamma \;\;\; e''=\alpha\delta\gamma$$
 $$e'=\alpha\beta\gamma \;\;\; e''=\alpha\delta\gamma$$
 With
 With
 - $\beta$ subexpression of $e'$
 - $\beta$ subexpression of $e'$
-- $\gamma$ subexpression of $e''$
-- $\gamma$ is a *choice* of $\beta$
+- $\delta$ subexpression of $e''$
+- $\delta$ is a *choice* of $\beta$
 
 
 ##### examples
 ##### examples
 - one step derivation
 - one step derivation
@@ -174,6 +174,10 @@ An __element__ can be a __terminal__ (alphabetic symbol) or a __compound object_
 ##### example:
 ##### example:
 List with separators and start-marker of end-marker
 List with separators and start-marker of end-marker
 $$ie(se)^*f\;\;\;i[e(se)^*]f$$
 $$ie(se)^*f\;\;\;i[e(se)^*]f$$
+i: inizio
+e: elemento
+s: separatore
+f:fine
 
 
 ### Substitution
 ### Substitution
 Operation that replaces the terminal characters of the source language with the phrases of the destination languages
 Operation that replaces the terminal characters of the source language with the phrases of the destination languages

BIN
Game Theory/.lesson_03.md.swp


+ 23 - 0
Game Theory/lesson_03.md

@@ -0,0 +1,23 @@
+# Game Theory - lesson 3
+#### 
+###### 12 October 2016
+## Extensive form
+
+### Example
+Three politicians must vote if to raise or not their salaries.
+Vote is public and in sequence. All of them want to raise the salaries
+but would like to vote against.
+
+#### Main Features
+1. The moves are in sequence
+2. Every possible situation is known to the players.
+At any time they know the past history and the possible developments.
+
+The complete game can be represented as a tree
+- The vertex representing the initial situation
+- The leaves representing the final situations of the game
+
+### Backward Induction
+We start from the final situation and we go back to the initial situation.
+A finite lenght is required for the game.
+

+ 17 - 0
OR/lesson_01.md

@@ -0,0 +1,17 @@
+# Operations Research - lesson 2
+#### Federico Malucelli
+###### 26 Sept 2017
+## Problems modeling
+
+---
+
+algorithm:
+- sort the indices by $\frac{c_i}{a_i}$
+- $remaining_budget \leftarrow b$
+- i<-1
+- repeat
+    * $y_1 \leftarrow min {1, \frac{remaining budget}{a_i}}$
+    * $remaining_budget \leftarrow remaining_budget - a_i*y_i$
+    * $i \leftarrow i+1$
+- until $i=n+1$ or remaining_budget = 0
+

BIN
Piattaforme Software per la Rete/.lesson_04.md.swp


+ 6 - 0
Piattaforme Software per la Rete/MOD1/genpdf.sh

@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+
+# Packages needed:
+# pandoc, texlive-core, texlive-latexextra 
+
+cat lesson_*.md | pandoc --latex-engine=xelatex -o course.pdf

+ 14 - 0
Piattaforme Software per la Rete/MOD1/lesson_00.md

@@ -0,0 +1,14 @@
+---
+fontsize: 12pt
+---  
+
+# Piattaforme Software per la Rete
+
+### Modulo 1
+    
+# Giacomo Verticale
+
+\pagebreak
+
+
+

+ 3 - 0
Piattaforme Software per la Rete/lesson_01.md → Piattaforme Software per la Rete/MOD1/lesson_01.md

@@ -130,3 +130,6 @@ Questo obiettivo non è stato pienamente perseguito, a causa della scelta del da
 - __prestazioni__
 - __prestazioni__
 - __mobilità__ (spostamento continuo)
 - __mobilità__ (spostamento continuo)
 - supporto al __nomadismo__ (collegamento in posti diversi)
 - supporto al __nomadismo__ (collegamento in posti diversi)
+
+
+

+ 99 - 0
Piattaforme Software per la Rete/MOD1/lesson_02.md

@@ -0,0 +1,99 @@
+# Piattaforme Software per la Rete - lesson 2
+#### Giacomo Verticale
+###### 11 March 2016
+## Modulo 1 - Endnodes
+
+__collo di bottiglia__ della velocità può essere
+- velocità del collegamento in uscita: serve link più veloce
+- in una delle funzioni dei nodi: si possono migliorare le prestazioni
+Le __astrazioni__ sono il primo nemico delle prestazioni
+Le comunicazioni ad esempio email non sono implementate direttamente sul cavo
+ ma ci sono multipli strati di astrazione, ognuno dei quali nasconde gli strati sottostanti. 
+La stessa __interfaccia__ (ad es socket) deve andare bene per applicazioni multiple
+ad esempio trasferimento di file (possibilmente lento) o pagine web (poss. veloce)
+
+Il nostro obiettivo è ottenere una velocità __wirespeed__
+
+## Endnodes
+__Struttura__: 
+- architettura a strati per *semplificare lo sviluppo*
+- sistemi di protezione
+- implementazione più generale possibile: ad es. scelgo algoritmi in base 
+al funzionamento generale e non al funzionamento in un caso specifico.
+__Scala__:
+La tabella di un pc desktop viene gestita da un algoritmo molto più semplice e meno sofisticato
+della tabella di un core router tra autonomous systems (~6 entries vs ~100'000 entries)
+
+### Architettura hardware BSD
+- Net Interface (scheda di rete che implementa lo strato ethernet)
+- I/O BUS
+- Bus Adaptor
+- System Bus
+- Memory
+- MMU + Cache
+- CPU
+La prestazione degli endnodes dipende molto dalla velocità della cache, 
+quindi si cerca di massimizzare l'utilizzo della cache. 
+Le cache in genere sono efficaci quando si ha una *località temporale* e *spaziale* tra le informazioni richieste. 
+Il caching non è sfruttabile facilmente nei sistemi di rete, ad esempio se si guarda un film in streaming, 
+non è utile mettere i pacchetti ricevuti in una cache, perchè i dati vicini non sono ancora arrivati, e
+quelli appena visti non serve mantenerli in cache. 
+Ad esempio se una macchina apre tante (~1000) connessioni TCP, non serve avere tutti i socket pronti in cache, 
+ma potrebbe essere utile copiare il descrittore del socket in cache nel momento in cui viene ricevuto un pacchetto. 
+Gli algoritmi BSD degli anni '80 non sono più adatti alle velocità (~300Mb/s) perchè sono adatti solo a velocità di (10-30Mbit/s). 
+
+### Architettura software BSD
+- Processi p1,p2,p3...
+- Kernel (coda IP)
+- Net Interface
+- Trama ethernet
+Quando la scheda di rete riceve una trama, questa viene copiata in un buffer,
+poi viene controllato il checksum, se non torna butto la trama, dopo
+viene controllato il MAC addr. se non è il mio butto la trama.
+La scheda di rete per interagire col S.O. alza un interrupt hardware
+La routine di gestione degli interrupt comunica alla scheda di mettere le trame sul buffer
+Può avvenire
+- Senza DMA: la CPU copia 1 byte per volta in RAM
+- Con DMA: la scheda di rete copia la trama direttamente in RAM
+A questo punto il pacchetto viene messo in una coda IP (nella memoria centrale)
+Del pacchetto guardo:
+- Indiritto IP destinazione, se non è il mio scarto o forwardo
+- Guardo campo protocollo (TCP o UDP)
+- Identifico socket tramite numero di porta sorg-dest (TCP) o dest (UDP)
+- Metto il pacchetto nella coda ad (es. UDP) del processo
+- Se il processo era in attesa bloccante, il processo viene cambiato a pronto
+- Quando verrà schedulato il processo va in esecuzione e legge dal socket. 
+Per un pacchetto TCP la questione è simile a parte la gestione della finestra,
+ad esempio se il pacchetto non è arrivato in ordine, non può essere consegnato
+finchè non arrivano i pacchetti mancanti.
+
+### Problemi
+__Livelock__
+Se il sistema è configurato male:
+- la scheda di rete riceve spesso pacchetti
+- il sistema operativo è troppo impegnato dagli interrupt della scheda di rete
+- il sistema non riesce a dividere i pacchetti nelle code
+- il sistema non riesce ad eseguire i processi che smaltiranno i pacchetti
+
+### Invio di un pacchetto
+Se consideriamo l'architettura hardware BSD con l'aggiunta di un disco sul bus I/O
+Ad un server può essere richiesta una pagina web tramite una richiesta HTTP GET
+- Il S.O. chiede al disco la pagina web richiesta e viene caricata in RAM (cache disco)
+- L'applicazione webserver legge dalla cache il file e lo copia nel proprio spazio utente
+- L'applicazione invoca la SEND sul socket buffer della connessione.
+- Il pacchetto viene copiato dal socket buffer alla scheda di rete
+Abbiamo 4 operazioni per ogni pacchetto, quindi la banda richiesta per ogni pacchetto viene
+amplificata di 4 volte.
+All'avvicinarsi della velocità del bus alla velocità del link aumenta 
+la latenza della trasmissione, e quindi il throughput della connessione non è determinato
+dal link ma dalla macchina che non riesce a gestire le connessioni.
+Ad esempio nei sistemi solaris l'applicazione invia i dati direttamente alla scheda di rete,
+senza passare dalla memoria, il checksum lo calcola la scheda di rete
+Anche la ricezione può essere ottimizzata facendo calcolare il checksum delle trame IP 
+in hardware alla scheda di rete. 
+Ad esempio in un datacente di Amazon vengono usate macchine virtuali che scambiano pacchetti tramite
+l'hypervisor facendo calcolare i checksum alla scheda di rete, a cui però i pacchetti non arrivano
+Quindi in questo modo si aveva un tasso di errore sui pacchetti molto alto.
+
+
+

+ 51 - 0
Piattaforme Software per la Rete/MOD1/lesson_03.md

@@ -0,0 +1,51 @@
+# Piattaforme Software per la Rete - lesson 3
+#### Giacomo Verticale
+###### 15 March 2016
+## Demultiplexing
+
+Un __sistema finale__(endnode) implementa l'intera pila protocollare dal livello fisico a quello applicativo
+I __nodi interni__ alla rete implementano un numero ridotto di livelli (1,2,3 e a volte 4).
+
+La __demultiplazione__ è lo spacchettamento della trama di livello 2 e tirare fuori il pacchetto di livello applicativo.
+- __Layered demultiplexing__ rispetta l'astrazione della stratificazione protocollare
+è possibile ottenere un implementazione semplificata ma più efficiente
+Ad esempio nel *video streaming* si usa UDP perchè TCP introduce affidabilità e ritardo
+- __Early demultiplexing__ Nel caso UDP venga bloccato, si può mascherare UDP da TCP, in occasioni come questa si gestisce tutta la pila
+protocollare a livello kernel(modulo del kernel) o a livello applicativo.
+Può servire a:
+- Prioritizzare i pacchetti
+- Usare codice specializzato
+- Saltare la pila protocollare.
+
+C'è un problema di __sicurezza__, in quanto un processo avrebbe accesso a tutti i pacchetti che transitano nel sistema.
+Vogliamo garantire __wirespeed processing__, il collo di bottiglia deve essere il link fisico.
+Vorremmo la proprietà di __composability__: Il costo complessivo deve essere minore alla somma dei protocolli attraversati.
+
+Lo standard attuale (usato ad esempio da wireshark o tcpdump) è il meccanismo __Berkeley Packet Filter__
+è un grafo di controllo di flusso (un qualsiasi grafo diretto aciclico).
+
+Il BPF viene eseguito nel kernel in parallelo (divisione di tempo OS) e gestisce gli stessi pacchetti 
+inviati allo stack TCP/IP layered, per ogni pacchetto ricevuto il BPF controlla se corrisponde ad alcuno dei filtri
+e nel caso viene copiato nel buffer corrispondente, altrimenti viene scartato.
+
+Il buffer serve perchè il costo di portare il pacchetto a livello utente è alto, e questo aumenterebbe il tempo
+di esecuzione del filtro, abbassando le prestazioni.
+La API si chiama __pcap__, e tcpdump è il programma più diffuso per usarle.
+--- Nota:
+*rarpd* è il nonno del protocollo DHCP e non viene più usato
+BootP consente di copiare informazioni per il boot
+DHCP consente di trasferire DNS, durata del lease, ecc.. 
+Per questo è inutile eseguire rarp in kernelspace ma basta eseguirlo in userspace, e lo stesso vale per lo sviluppo 
+di nuovi protocolli.
+Il filtro viene specificato usando una sintassi BPF che viene compilata ed eseguita nella virtual machine BPF
+(Originariamente pseudo-machine) VM-BPF ha un suo set di istruzioni limitato e specifico.
+
+### BPF syntax
+### Tcpdump and wireshark
+__Tcpdump__ stampa pacchetti in stdout, e può salvare pacchetti in file pcap
+__Wireshark__ dispone di filtri aggiuntivi per riconoscere traffico a livello applicativo.
+I pacchetti salvati nel formato pcap vengono tagliati ai primi 64byte ad esempio per salvare solo gli header utili
+senza memorizzare tutto il pacchetto sprecando spazio.
+
+
+

+ 70 - 0
Piattaforme Software per la Rete/MOD1/lesson_04.md

@@ -0,0 +1,70 @@
+# Piattaforme Software per la Rete - lesson 4
+#### Giacomo Verticale
+###### 17 March 2016
+## Exact Match Lookup
+## Bridge Ethernet
+Il primo bridge ethernet è nato per connettere due reti separate
+Il problema di usare solo un ripetitore per connettere due reti
+è che fonderei le due reti portando dalle due parti molto traffico inutile.
+
+Il __bridge__ presenta due interfacce e ha una tabella di routing
+- Se il destinatario della trama si trova nella stessa interfaccia
+da cui è arrivata la trama, questa non viene propagata
+- Se il destinatario è nell'altra interfaccia,
+la trama viene propagata
+Il bridge ha un __algoritmo di apprendimento__ con cui si annota l'interfaccia
+da cui provengono le varie trame per poter effettuare forwarding.
+
+### Requisiti prestazionali
+- Lunghezza trame ethernet = 64Byte (max=1500Byte)
+Fissata dal requisito di distanza massima della rete
+Le trame internet più diffuse sono ack (40byte+14 intestazione)
+Quindi vengono inviati 64-54Byte=10Byte inutilmente
+- Velocità del collegamento = 10Mbit/s
+- Tempo tra 2 trame = 64x8bit/10Mbit/s = 51,2us
+
+Nel tempo tra 2 trame le operazioni da fare sono:
+- (sovra)Scrivere la riga della tabella
+- Leggere la riga corrispondente
+Queste operazioni vanno fatte per 2 interfacce allo stesso tempo
+Quindi ho 4 operazioni di lookup per ogni intervallo
+Ovvero 1 lookup ogni 12,8us
+
+Di solito in questi algoritmi il limite alle prestazioni è 
+il singolo accesso a memoria, mentre le operazioni aritmetiche hanno un
+impatto trascurabile.
+
+Il primo bridge Dec aveva un tempo di accesso a memoria di 100ns
+Max numero di righe= 8000
+Soluzione: array ordinato
+Max n. accessi a memoria= log2(8000)=13
+Costo di lookup = 1,3us
+
+### Tecnologia FDDI
+è una tecnologia di rete ad anello,
+ha lunghezza minima della trama 40Byte
+Velocità= 100Mbit/s
+Tempo tra 2 trame = 3.2us
+
+Per migliorare le prestazioni si potrebbero usare memorie più veloci
+ma questo alzerebbe il prezzo sul mercato, :(
+Per questo è stato introdotto l'uso delle __tabelle hash__
+Che consistono in una funzione di hash che mappa gli input in un array con indici di n bit
+Nel caso peggiore dell'utilizzo di una hash table, tutti i mac finiscono nella stessa chiave, 
+quindi ho tempi di accesso analoghi ad una tabella
+Se ho una funzione di hash abbastanza buona da non avere collisioni, ho tempo di accesso costante
+Se inizio ad avere tante collisioni, posso cambiare la funzione di hashing
+Quello che si fa di solito è avere una famiglia di funzioni di hashing, 
+ne scelgo una a caso e valuto le prestazioni, se va male cambio la funzione e ne scelgo un'altra.
+
+Originariamente si era pensato ad un albero di 3 livelli invece ad una lista,
+questo permette di avere al massimo 7 collisioni
+Nell'implementazione del gigaswitch in caso di collisione si utilizzava una CAM ovvero una memoria
+che era in grado di fare ricerca in parallelo in hardware.
+
+MAC 48bit A(x)=a0x^47+a1x^46+...+a46x+a47 Sono i bit del mac address
+H(x)=A(x)M(x)modG(x)
+output,input,parametro che determina una specifica funzione hash
+
+
+

+ 129 - 0
Piattaforme Software per la Rete/MOD1/lesson_05.md

@@ -0,0 +1,129 @@
+# Piattaforme Software per la Rete - lesson 5
+#### Giacomo Verticale
+###### 18 March 2016
+## Prefix Match
+
+Per ogni pacchetto viene fatto il matching nella tabella di inoltro
+In caso di ambiguità di applica la regola del __Longest prefix matching__
+Cioè data una chiave, dobbiamo trovare la riga contenente il prefisso più lungo.
+
+### Osservazioni
+Potremmo usare una cache per le voci più usate
+Il costo finale della ricerca sarà una media pesata del costo 
+per la ricerca in cache e del costo per la ricerca fuori,
+quindi è utile solo in caso di alta probabilità di usare la cache (~90-95%)
+Nei router con tabelle molto grandi, gli indirizzi utilizzati sono molto vari
+
+- 1 molti flussi contemporaneamente
+	- molti indirizzi diversi in un intervallo breve
+- 2 ~50% dei pacchetti sono TCP SYN e/o ACK ~40byte
+	- Quindi il tempo di interarrivo è all'incirca quello dei pacchetti di
+lunghezza minima, quindi ho poco tempo per risolvere gli indirizzi.
+- 3 Il costo della ricerca è dominato dal tempo di accesso in memoria
+Perchè ci sono solo operazioni aritmetiche semplici da effettuare.
+- 4 Capita di trovare prefissi di tutte le lunghezze (non solo 24)
+- 5 ~100'000 di righe 
+Con IPv6 la situazione peggiora perchè ci sono altri indirizzi e le netmask vanno da 8 a 64bit
+- 6 Aggiornamenti frequenti (ms-s) devo usare algoritmi con letture e scritture bilanciate.
+	- Ci sono algoritmi che hanno ottime prestazioni in lettura ma quelle in scrittura sono disastrose
+ce ne sono altri che hanno delle buone velocità in scrittura ma meno in lettura
+
+### Soluzione
+Una soluzione ottima che richiede budget molto elevato è tutta in hardware
+Le CAM hanno una tabella chiave-valore
+chiave = {0,1}^n
+è utile una variante: TCAM (ternary)
+chiave = {0,1,*}^n (*:wildcard)
+Gli * possono essere in qualsiasi posizione, noi li metteremo alla fine.
+La CAM può restituire al più 1 risultato, nella TCAM potrebbe succedere
+Il problema si risolve mettendo una preferenza tra le voci
+Cioè vince il prefisso più in alto, per questo è necessario ordinare
+le voci mettendo il prefisso più lungo in alto (inserimento più costoso
+rispetto ad una CAM normale usata nel Exact Matching)
+
+__Vantaggio__
+Tempo di ricerca costante in lettura
+__Svantaggi__
+- Rispetto ad una memoria normale, utilizza più transistor (10 rispetto a 1-2)
+Questo posta ad un costo più elevato per circuito (chip per area)
+Quindi consumano anche molto di più
+`In italia il primo consumatore di energia sono le ferrovie, il secondo è telecom`
+Ultimamente si utilizzano meno le TCAM e si usano invece memorie veloci 
+con algoritmi molto ottimizzati e Cisco ha ottenuto anche un algoritmo 
+con due accessi alla memoria (dinamica) per entry (e un numero fisso di accessi in cache).
+vedi successivamente multibit trie.
+Quindi le TCAM vengono usate in dispositivi di fascia media perchè per router
+troppo grossi non sono abbastanza capienti, e per router piccoli sono costose.
+
+### Algoritmo
+Supponiamo di avere una TCAM già popolata con prefissi di lunghezza decrescente
+Se dobbiamo inserire un indirizzo in mezzo ad altri ma non c'è spazio
+Inserendo un indirizzo di lunghezza 31 lo mettiamo a posto del primo di lunghezza 30
+che dobbiamo riposizionare, in questo modo avremo max 32 riposizionamenti.
+Un implementazione furba ha gli indirizzi lunghi sopra, quelli corti sotto e un buco in mezzo.
+
+### Soluzioni algoritmiche
+Algoritmi basati su:
+- __Tries__ ha prestazioni migliori ma i più efficienti sono brevettati
+- __Ricerca binaria__
+
+__Unibit trie__
+```
+Tabella di routing
+P1=101*
+P2=111*
+P3=11001*
+P4=1*
+P5=0*
+P6=10000*
+P7=100000*
+P8=100*
+P9=110*
+```
+__Nodo dell'albero__
+
+Prefisso/valore | -
+ ---- | ----
+ 0 | 1
+
+Il primo blocco è il puntatore al prossimo livello sul ramo 0
+Il secondo è il puntatore al prossimo livello sul ramo 1
+__Radice dell'albero__
+
+ Root | -
+ ---- | ----
+ 0-P5 | 1-P4
+
+ P5 | -
+ ---- | ----
+ - | - 
+
+ P4 | -
+ ---- | ----
+ sottoalbero | s.a.
+
+ - | -
+ ---- | ----
+ 0-P8 | 1-P1
+
+ecc...
+Ogni livello indica la lunghezza del prefisso.
+
+__Visita dell'albero__
+Se dobbiamo cercare un indirizzo nell'albero
+iniziamo a scorrerlo dalla radice annotando l'ultimo nodo per cui passiamo
+Quando non possiamo più procedere l'ultimo nodo per cui siamo passati è la route cercata.
+
+__Tempi di accesso__
+Costo nel caso pessimo: 32 accessi in memoria
+In generale è possibile scambiare occupazione di memoria con tempo di calcolo
+Utilizzando un __multibit trie__ che ha per ogni nodo molti figli (es.4)
+Il problema dei multibit trie è che posso memorizzare solo prefissi che
+hanno lunghezza multipla intera del passo dell'albero, se ho prefissi più corti 
+devo esploderli in più nodi di lunghezza intera. (1*3bit -> 2*4bit)
+
+Se ho una tabella data, esiste un passo che ottimizza i tempi di accesso
+Però gli inserimenti sono critici perchè si sposta il punto di ottimo.
+
+
+

+ 138 - 0
Piattaforme Software per la Rete/MOD1/lesson_06.md

@@ -0,0 +1,138 @@
+# Piattaforme e Software per la rete - lezione 6
+#### Giacomo Verticale
+###### 22 March 2016
+## IP Prefix Match
+Più sofisticato rispetto all'exact match degli switch ethernet
+Serve che tutti gli indirizzi abbiano un tempo di risoluzione uniforme
+La famiglia di algoritmi basati su *trie* sono molto diffusi per IPv4
+Gli algoritmi di ricerca binaria danno risultati dignitosi in IPv4
+e stanno tornando di interesse per IPv6 in quanto le ottimizzazioni 
+di IPv4 non sono più efficaci.
+
+Possiamo costruire facilmente la *ricerca esatta*, quindi posso ricondurre
+la ricerca generica alla ricerca esatta, come nel
+L'algoritmo __binary search on prefix lenghts__
+- Ho un array con lunghezze diverse per ogni elemento
+Ad ogni elemento corrisponde una hashtable con i prefissi di quella lunghezza.
+
+L'algoritmo applicato all esempio precedente
+```
+0* - 101* 1000* 11001* 100000*
+1*   111* 
+     100*
+     110*
+```
+Il __costo computazionale__ per una ricerca lineare nell'array
+nel caso pessimo (prefix length=0) porta a 32 accessi,
+Posso migliorare questa resa fino a log2(32) usando ricerca binaria.
+
+Esempio:
+Iniziando la ricerca binaria da l=16
+- Se trovo un match posso escludere la parte sinistra perchè 
+il longest match sarà sicuramente a destra
+- Se non lo trovo non so dire se è a destra o sinistra.
+
+Aggiungo un *marcatore* per segnare un punto all'interno dell'array 
+uguale al prefisso da cercare, in modo che se la ricerca a destra 
+non porta risultati, devo cercare a sinistra.
+
+## Packet Classification
+Stiamo trattando il livello 4, che in teoria dovrebbe essere
+implementato solo a livello di host, ma i nodi interni alla rete
+possono sbirciare nei pacchetti per implementare funzioni aggiuntive
+ad esempio *NPAT*(NAT con modifica dei numeri di porta), oppure i *firewall*
+Questi oggetti non implementano la macchina a stati TCP ma gestiscono
+i pacchetti intermedi.
+
+__Middlebox__ è un nodo interno della rete che non è un host ma nemmeno un router
+Hanno funzioni molto diverse, in Internet circa 50% dei nodi sono middlebox.
+Storicamente i middlebox erano dei *pizzabox* da inserire nei rack del datacenter,
+ma ultimamente si tende alla *dematerializzazione* di questi dispositivi.
+
+Esempi di middlebox sono:
+- __NPAT__ Fanno Network Port Address translation
+- __Firewall__ Impediscono o meno il passaggio di determinati pacchetti
+- __WAN Accellerator__ Gestiscono la differenza di velocità tra reti, per evitare
+la formazione di code lunghe ad esempio tra dorsare e rete mobile o adsl.
+*Nota*: ad esempio nel caso di streaming video su rete mobile la rete fa il 
+prefetching dei contenuti del video richiesto e quando i contenuti sono finiti, 
+ne vengono chiesti altri
+- __L4 Switch__ violano la separazione dei layer e fanno routing ottimizzando 
+in base ad informazioni prese dal livello 4
+- __L7 Switch__ fanno routing in base al livello applicativo
+
+All'interno di un middlebox possono esserci ~10'000-100'000 regole per gestire i pacchetti. 
+I pacchetti sono classificati in base ad un set di regole: __Ruleset__ o __Database__. 
+Ogni regola ha una *priorità* per disambiguare nel caso di match multipli.
+Problema della __Packet classification__ consiste nel trovare la regola corrispondente
+a massima priorità o a costo minimo. (in ogni caso numero d'ordine più basso)
+
+Le regole sono __multifield__
+Ogni regola da delle condizioni su uno o più campi del pacchetto, quindi guarda
+fino a K campi distinti del pacchetto.
+Ogni campo è una stringa di bit di lunghezza fissata.
+*Nota*: la posizione del campo nel pacchetto dipende da altri campi.
+Sono consentiti 3 tipi di corrispondenza per ogni campo:
+- __Exact match__ es: TCP con porta 80
+- __Prefix match__ es: indirizzi IP
+- __Range match__ es: un certo intervallo di porte
+ 
+Classificatore = {R1,R2,...Rn} Ri=regola i-esima
+Regola = (regola campo 1, regola campo 2,.. regola campo K)
+Ad ogni regola è associato un costo o priorità, e una direttiva (insieme di azioni da compiere)
+
+Abbiamo una rete 'Net' con due host 'M' e 'TI', alla rete Net è collegato un middlebox.
+Al middlebox è attaccata un altra rete con due host 'TO' e 'S'
+
+TI e TO sono due server del tempo che usano il protocollo NTP
+
+Esempio di possibile ruleset per un firewall (non unica applicazione possibile):
+
+DEST IP | SORG IP | DST P | SRC P | PROTO | FLAG
+    --- | --- | --- | --- | --- | ---
+   M    |  -  |  25 | -   | TCP | -
+   M    |  -  |  53 | -   | UDP | -
+   TI   |  TO | 123 | 123 | UDP | -
+   -    | Net |  -  |  -  |  -  | -
+   Net  |  -  |  -  |  -  | TCP | ACK
+   -    |  -  |  -  |  -  |  -  | -
+
+La penultima regola fa passare tutti i pacchetti a parte il SYN iniziale
+L'ultima regola matcha tutti gli altri casi, generalmente per un firewall 
+il comportamento di default è bloccare (whitelisting), ma potrebbe
+essere diverso per un altro middlebox.
+
+### Requisiti prestazionali
+- Classificazione __wirespeed__
+Posso sempre scambiare utilizzo di memoria con prestazioni, usando 
+ad esempio strutture dati replicate per il ruleset.
+- Occupazione di memoria piccola
+- Inserimento / cancellazione infrequenti
+- Sono generalmente *stateless* ma possono essere *stateful*
+Esempio: __firewall stateful__ che quando rileva un pacchetto SYN uscente aggiunge 
+una rule per far passare gli ACK entranti per consentire quella connessione.
+Esempio2: Middlebox che bloccano tentativi di accesso anomali (es: fail2ban)
+
+### Ricerca lineare
+Va bene quando ho pochi elementi
+Posso abbinarla ad un caching per le ultime regole usate.
+Ricordando che la località dei pacchetti è relativamente bassa, 
+rispetto ad esempio ad un accesso su disco.
+Attenzione a basso *hit ratio* (~80-90%)
+Il problema è che se un pacchetto fa match nella cache, posso avere fuori
+dalla cache una regola a priorità più alta
+Quindi conviene copiare in cache gli header dei pacchetti della stessa connessione,
+in modo da riconoscere pacchetti della stessa connessione.
+ 
+### Passare etichette
+E un approccio di 'thinking out of the box', e consiste nel delegare la 
+classificazione ad altri, ad esempio ai router di frontiera che hanno un
+flusso minore e hanno più tempo per classificare i pacchetti, quindi:
+- Nodi di frontiera fanno classificazione multi-field e applicano tag
+- Nodi interni fanno exact match sui tag (es: MPLS, DIFFSERV)
+
+### BPF 
+PacketFilter usato negli host in modo efficace, ma molto lento se usato nei router.
+
+
+

+ 38 - 0
Piattaforme Software per la Rete/MOD1/lesson_07.md

@@ -0,0 +1,38 @@
+# Piattaforme e Software per la rete - lezione 7
+#### Giacomo Verticale
+###### 1 April 2016
+## Middleboxes
+Una soluzione è usare le TCAMs nelle packet classification, ma sono grosse e consumano molto,
+non hanno un estensione ulteriore per il range match, se ho un range di 50 valori dovrei creare 50 regole.
+Ma posso giocare coi prefissi per ridurre il n° di regole.
+Guardiamo un campo di IPv6: __flow label__, viene messo dentro di esso un numero a caso di 20 bit,
+che verrà replicato in tutti i pacchetti dello stesso flusso.
+Lo scopo di avere un campo di questo tipo è consentire ai nodi intermedi di prendere decisioni
+di packet classification guardando solo il livello 3, senza andare a livello 4 (che potrebbe 
+non essere accessibile per via della crittografia).
+Uso gli ultimi bit del flow label per indirizzare i pacchetti che appartengono ad uno stesso flusso
+per la stessa strada.
+La sorgente potrebbe non mandare pacchetti dello stesso flusso con lo stesso numero flow,
+perciò i nodi intermedi potrebbero non fidarsi della sorgente.
+Oltre al flow label nella cache mando anche gli altri campi importanti in modo che possa confrontarli.
+
+So fare molto bene i match uno per volta ma ho difficoltà a farlo di più campi contemporaneamente.
+Quindi: trovo tutte le regole che matchano campo 1 poi quelle che matchano campo 2, le tengo tutte
+e ne faccio l'intersezione (AND), e trovo quelle che matchano con tutti i campi.
+
+Per fare l'and bit a bit (bitwise) è lineare il costo.
+Se ho tutti zero non ho un match, se ho almeno un 1 sì.
+
+## Switching
+La memoria condivisa funziona solo per poche porte e link lenti.
+Nelle architetture a bus si salta la memoria, il pacchetto viene salvato direttamente sulla porta d'uscita 
+partendo dalla memoria d'ingresso.
+Ci sono varie versioni in base al numero di CPU:
+- Quella ad una CPU prende essa tutte le decisioni di forwarding
+- Con più CPU si alleggerisce il carico computazionale, 
+Si presentano pacchetti in cui i *lookup*sono fatti già sulle line card, 
+non sovraccaricando la CPU che gestisce solo il piano dati.
+Un'altra soluzione è avere una __matrice crossboard__
+
+
+

+ 59 - 0
Piattaforme Software per la Rete/MOD1/lesson_08.md

@@ -0,0 +1,59 @@
+# Piattaforme e Software per la rete - lezione 8
+#### Giacomo Verticale
+###### 8 April 2016
+## Switching
+
+Gli switch pososno essere realizzati con tecniche diverse:
+- Architettura a BUS
+- Matrice di crossbar:
+Una matrice con un bus per ogni coppia ingresso uscita
+L'architettura __crossbar__ ha il difetto di essere costosa
+Ci sono architetture a più stadi che permettono di ottenere lo stesso
+livello di connettività con metto punti di incrocio necessari.
+Lo __scheduling della crossbar__ consiste nel decidere in ogni istante di tempo
+quali ingressi devono parlare con quali uscite.
+
+Il nostro obiettivo è:
+##### Massimizzare il numero di connessioni ingressi/uscita contemporanei.
+
+I problemi sono:
+- In ogni istante di tempo ogni ingresso/uscita deve trasmettere un pacchetto.
+- Può esserci una contesa su una porta in usita.
+
+### Algoritmi per crossbar scheduling
+#### Take a ticket
+Lavora in modo asincrono.
+Ogni *line card* (uscita) mantiene una coda distribuita per i pacchetti destinati ad essa.
+Per gestire i ticket non è necessaria una crossbar alternativa, ma basta un bus a contesa.
+Le fasi di una ipotesi sincrona sono:
+- Gli ingressi chiedono un ticket per il pacchetto più vecchio in base alla destinazione
+- L'ordine con cui vengono servite le interfacce dipende dall'algoritmo utilizzato, es: round robin
+Questo algoritmo è affetto da __head-of-line-blocking__ in quanto i pacchetti successivi al primo
+non vengono processati prima del primo anche se le loro uscite sono disponibili.
+- In un round successivo viene servita la porta successiva, che trasmette se la porta necessaria
+non è già occupata in una trasmissione.
+
+In condizioni di traffico uniforme il rendimento di questo algoritmo è del 63%
+Dato che l'efficienza non è del 100%, se tutte le interfacce sono attive, si formerà una coda.
+
+Strategie per rimediare all'head-of-line blocking.
+- Aumentare la velocità del bus interno rispetto alla velocità degli ingressi.
+Nei sistemi reali uno speedup di 4X risolve i problemi di efficienza.
+- __Virtual Output Queues__ alternativo all'Input Queuing, in cui le code
+non sono all'uscita ma all'entrata: ogni ingresso ha una coda per ogni uscita.
+
+#### Parallel Iterative Matching
+Diverso dal take a ticket per:
+- Virtual Output Queuing invece di Input Queuing
+- Richiede pacchetti di dimensione fissa e tempo in slot.
+
+PIM è intrinsecamente randomizzato, feature che non serviva in TaT per l'asyncronicità
+Fasi dell'algoritmo:
+- Richiesta: tutte le porte di ingresso spediscono informazioni sullo stato tramite una bitmap.
+(stringa di bit lunga come #code, se è vuota bit=0 se ci sono pacchetti bit=1)
+- Grant: Ciascuna uscita sceglie una porta di ingresso da servire,
+se un uscita riceve richieste da più porte di ingresso, ne sceglie una a caso.
+- Accept: Ogni ingresso sceglie un uscita, se ce ne sono multiple viene scelta a caso.
+
+
+

+ 125 - 0
Piattaforme Software per la Rete/MOD1/lesson_09.md

@@ -0,0 +1,125 @@
+# Piattaforme e Software per la rete - lezione 9
+#### Giacomo Verticale
+###### 12 April 2016
+## Router pt.2
+
+Dei pacchetti che arrivano nel router viene separata l'intestazione che viene inviata al meccanismo di lookup.
+Le code nell'algoritmo take-a-ticket sono negli ingressi, le uscite sono molto semplici.
+Negli algoritmi tipo *pim* in cui si usano meccanismi di speedup interni, alzando la velocità della
+matrice di commutazione rispetto alla velocità degli ingressi/uscite
+
+### Gestione delle code in uscita
+#### Gestione del buffer
+I buffer sono di capacità finita quindi prima o poi si riempono e serve scartare i pacchetti.
+La politica di __scheduling__ determina quale pacchetto viene spedito sull'interfaccia di uscita
+che può essere quello più vecchio ma non necessariamente.
+
+__Soluzione base__
+- Gestione buffer __tail drop__: accetto pacchetti finchè il buffer è pieno
+- Scheduling fifo
+Questa soluzione base va bene per carichi leggeri.
+Il caso di test tipico è una connessione TCP perchè sono molto diffuse in internet.
+```
+|
+|
+|       -
+|     -
+|   -   
+|  /
+| /
+|-
+|
+---------------------->
+slow
+start
+```
+La crescita è esponenziale durante slow start e lineare una volta superata SSTHRESH
+- Fase esplorativa: congestion avoidance
+La differenza fra TCP Tahoe e TCP Rhyno è che a seguito di una perdita di un pacchetto
+in Tahoe si aspetta il TimeOut e si va a velocità 1, Rhyno usa un meccanismo di __fast recovery__
+che controlla il pacchetto perso nella sequenza e dimezza la velocità e abbassando SSTHRESH
+si riparte con crescita lineare.
+
+Il meccanismo di __crescita additiva__ e __decrescita moltiplicativa__ raggiunge
+un buon compromesso tra aggressività ed efficienza.
+
+I pacchetti TCP vengono inviati a burst, e arrivati ad una cerca velocità il nodo inizia a *scartare pacchetti*
+Il buffer impiega del tempo per svuotarsi, e c'è un alta possibilità che i pacchetti persi siano della stessa
+connessione, questo crea problemi al meccanismo di fast retrasmit che riesce a recuperare solo buchi di pochi pacchetti.
+Il risultato è che avendo perdite multiple si disattiva __fast recovery__, scatta Timeout e si va a velocità 1.
+
+Quindi la gestione __taildrop__ porta a perdite multiple di una stessa connessione, inoltre una volta
+che avviene un *buffer overflow* vengono penalizzate anche le sorgenti che non hanno causato la perdita
+di pacchetti.
+Inoltre ho sincronizzato la forma del throughput delle sorgenti, quindi le sorgenti si sommano nei picchi
+e negli avvallamenti e quindi non posso raggiungere una velocità elevata.
+L'ultimo problema è che la notifica della perdita di pacchetti avviene dopo quest'ultima,
+in questo modo è impossibile evitare la perdita riducendo la velocità.
+
+__Obiettivi__ per un buffer scheduling
+- Segnalare una congestione immminente alle sorgenti tcp più attive.
+- Garantire *fairness* tra sorgenti anziane e giovani (anziane hanno priorità)
+- Fornire garanzie di banda e ritardo per flusso (QoS)
+
+ ### Random Early Detection (RED)
+è un algoritmo di gestione del buffer, decide quali pacchetti ammettere nel buffer.
+- Scarto pacchetto con probabilità p
+THR equilibrio TCP è proporzionale a MSS/(RTT* sqrt(p))*
+Se il nodo è il collo di bottiglia, il punto di lavoro rimane sulla retta lineare della threshold.
+```
+|
+|
+|
+|
+|        /
+|       /
+|      /
+|_____/
+|-----------------------
+     min   max
+    thresh thresh
+```
+
+Il problema è che tutte le connessioni piccole, ad esempio quelle per richiedere una pagina web
+non sfruttano il meccanismo di congestion window TCP
+
+#### Varianti
+- Stimatori autoreferenti
+occupazione media(t)
+(1-alpha)*occupazione media(t-1)
++ alpha*occupazione attuale
+
+- Una variante di questo modello è un meccanismo che utilizza curve diverse per ogni classe di applicazioni
+e si chiama __Weighted RED__
+- __RED for in and out__
+
+### Politiche per allocazione di banda
+__FIFO__
+- Allocazione proporzionale alla richiesta di banda
+- Nessuna protezione da sorgenti greedy
+- Semplice da implementare
+
+__Priorità semplice__
+- Richiede code multiple
+- Richiede un classificatore
+- Serve in ordine di priorità
+- Servizio può essere interrompibile o non interrompibile
+Nel caso di collegamenti lenti (~10Kbit/s) ha senso distinguere tra trasmissioni interrompibili o non.
+Nelle reti moderne non viene effettuato il blocco della trasmissione di un pacchetto per trasmetterne
+un altro perchè il tempo richiesto a trasmettere il pacchetto è poco.
+
+Funziona abbastanza male se le priorità sono tante perchè i pacchetti a priorità bassa
+soffrono di starvation.
+Per risolvere questo problema, alla alta priorità viene associato un limite sulla banda utilizzata
+
+__Round Robin__
+- Necessita di un classificatore
+- Una coda per classe
+- Servo un pacchetto per ogni coda.
+- Se i pacchetti hanno lunghezza variabile funziona molto male.
+Per rendere fair round robin con dimensioni variabili si cerca di di simulare il round robin bitwise che
+è fair per definizione, ad esempio si effettua un round robin bitwise e quando viene selezionato il bit finale
+di una coda, viene inviato il pacchetto corrispondente, in questo modo si ottiene una distribuzione uniforme.
+
+
+

+ 131 - 0
Piattaforme Software per la Rete/MOD1/lesson_10.md

@@ -0,0 +1,131 @@
+# Piattaforme e Software per la rete - lezione 10
+#### Giacomo Verticale
+###### 15 April 2016
+## Scheduler Deficit Round Robin (DRR)
+Lo scheduler round robin classico risulta iniquo nel caso ho pacchetti 
+di dimensione variabile, una delle implementazioni per simulare un round 
+robin su pacchetti di dimensione variabile è il __Deficit Round Robin__
+
+Ho una serie di code su cui accumulo ad ogni turno una serie di permessi
+Se i permessi sono sufficienti a trasmettere, posso trasmettere,
+altrimenti li accumulo.
+Per ogni coda ho:
+- Qi (quanto) costante nel tempo
+- Di (deficit) variabile nel tempo
+
+Quando visito la coda i-esima calcolo il nuovo Di
+Di = Di + Qi
+Finchè Di >= Li (Li= lunghezza primo pacchetto)
+trasmetto il primo pacchetto.
+Quando la coda che sto servendo non ha più pacchetti, non accumula deficit,
+La mia idea è di trasmettere qualcosa ad ogni iterazione, per questo posso
+fare il quanto grande come il più grande pacchetto possibile.
+Faccio in modo che rimangano nella lista solo le code attive:
+- Le code che hanno trasmetto vengono messe in fondo alla coda dopo la visita
+- Le code che non hanno più pacchetti da trasmettere vengono rimosse dalla lista.
+
+### Esempio
+CODE:
+- 20,750,200
+- 500,500
+- 200,600,100
+- 50,700,180
+Qi=500 per ogni i
+Simulare DRR indicando ad ogni tempo Di quali pacchetti sono trasmessi
+
+Round | Coda | Di iniziale | Di finale | L pacchetto Tx | FineTx
+---   | ---  | --- | --- | --- | ---
+1     | 1    | 0   | 300 | 200 | 200
+1     | 2    | 0   | 0   | 500 | 700
+1     | 3    | 0   | 400 | 100 | 800
+1     | 4    | 0   | 320 | 180 | 980
+2     | 1    | 300 | 50  | 750 | 1730
+2     | 3    | 400 | 300 | 600 | 2850
+2     | 3    | 300 | 0   | 200 | 3050
+2     | 4    | 120 | 0   | 50  | 3800
+
+## Esercizi
+### Esercizio Algoritmo RED
+Assumendo lunghezza media della coda costante, calcolare
+la distribuzione di probabilità e valore atteso
+del numero di pacchetti tra due eventi di scarto successivi
+nei due casi:
+- il nodo scarta con probabilità p
+- il nodo scarta con probabilità pd = p /1-cp  con c= numero di pacchetti da ultimo scarto
+
+a: chiamo X il numero di pacchetti tra due scarti
+`Pr(X=x) = (1-p)^X*p`
+x | Prob
+--- | ---
+0 | p
+1 | (1-p)p
+2 | (1-p)^2p
+
+è una distribuzione di tipo geometrico (quanti fallimenti prima di un successo)
+
+b: Pr(X=x) = p / 1-(x-1)p
+$ p/(1-(x-1)p) /sigma^(x-2)_(c=0) (1-p/(1-cp)) =$ //p se 1<=x<= 1/p
+
+
+### Esercizio di classificazione
+_p
+- Definire il bitvector per ogni campo
+- Applicare l'algoritmo a (A,D,80,23,TCP)
+Ip Src | IP Dst | Port Src | Port Dst | Prot
+---    | ---    | ---      | ---      | ---
+A      |    *   |   53     |    80    | UDP
+B      |    C   |   123    |    80    | *
+A      |    D   |   80     |    *     | TCP
+*      |    E   |   *      |    25    | TCP
+
+Il __bitvector__ indica su quali regole matcha il pacchetto
+IP sorgente | bitvector
+--- | ---
+A | 1011
+B | 0101
+* | 0001
+
+IP destinazione | bitvector
+--- | ---
+C | 1100
+C | 1010
+E | 1001
+* | 1000
+
+Port Src | bitvector
+--- | ---
+53 | 1001
+123 | 0101
+80 | 0011
+* | 0001
+
+Resta da effettuare l'AND dei bitvector dei campi
+Campi | bitvector
+--- | ---
+A | 1011
+D | 1010
+80 | 0011
+23 | 0010
+TCP | 0111
+res | 0010
+
+### Esercizio prefissi IP
+Per codificare un prefisso di lunghezza variabile usando 33 bit
+usiamo il seguente algoritmo:
+Scriviamo i bit del prefisso seguiti da 1 e poi zeri fino a 33 bit
+- Dire quanti sono i possibili prefissi di 32bit
+- Codificare 128.0.0.0/2 128.0.0.0/3 128.0.0.0/4
+
+### Esercizio Unibit Trie
+Mostrare che il massimo numero di nodi è O(NW)
+con 
+- N = numero di prefissi e 
+- W= lunghezza massima prefisso
+Suggerimento: costruire un trie con log2N livelli e poi aggiungere
+a ogni foglia una stringa di W-log2N bit
+
+(W-log2N)N/2+N/2-1
+O(W*N)
+
+
+

+ 91 - 0
Piattaforme Software per la Rete/MOD1/lesson_11.md

@@ -0,0 +1,91 @@
+# Piattaforme e Software per la rete - lezione 11
+#### Giacomo Verticale
+###### 19 April 2016
+## Misura del traffico internet
+La rete internet funziona abbastanza per quanto riguarda
+la consegna a destinazione dei pacchetti,
+per quanto riguarda le prestazioni, c'è bisogno di lavoro
+per __ingegnerizzare la rete__ 
+Fasi:
+- Misura del traffico: è necessario effettuare
+aggiornamenti della rete per tenere il passo con 
+la richiesta sempre maggiore, l'aggiornamento viene effettuato
+tenendo conto di alcune priorità
+    - input A: pianificazione della capacità
+    - accounting (billing): classificare il traffico
+    - analisi del traffico
+
+### Matrice di traffico
+Il routing di internet è *topology driven*, ed è una
+limitazione in quanto non c'è la possibilità di bilanciare
+l'utilizzo delle risorse, ad esempio sfruttando link paralleli.
+
+è una tabella che riporta per ogni coppia di nodi, quanto traffico
+entra da un nodo per andare all'altro (bit/s)
+Questa matrice viene costruita per i nodi che stanno sul confine della
+rete da considerare.
+Con N nodi sul confine abbiamo una tabella di N^2 nodi,
+con gli elementi sulla diagonale nulli, quindi N(N-1) incognite.
+Il traffico è un parametro che cambia nel tempo quindi la matrice
+sarà in funzione del tempo, anche se in questo caso consideriamo
+un tempo fissato.
+Viene sfruttato il meccanismo dell' __interface counting__ che è una
+feature presente in tutti i router e indica quanti byte o pacchetti
+sono transitati per ogni interfaccia.
+Ogni interfaccia porta a due equazioni di N incognite (una per il traffico
+in ingresso e una per quello in uscita)
+In totale ho 2N equazioni in N^2 incognite, quindi non posso risolvere le equazioni
+Dato che il numero di incognite è praticamente fisso, mi serve 
+__aumentare il numero delle equazioni__ e posso farlo
+aumentando i contatori per interfaccia (es: differenziandoli per ip o servizio)
+- Questo può portare a *milioni di contatori*.
+- Un pacchetto fa incrementare più di un contatore
+- lunghezza dei contatori
+
+Normalmente per ogni contatore si considerano 64bit, per milioni di contatori
+la memoria occupata diventa molta e non è possibile tenerli in memoria cache.
+Una strategia efficace è tenere in cache i c bit più significativi di tutti i
+contatori, suddividendoli in *verticale*
+La probabilità di andare in overflow avendo pochi bit è elevata, quindi serve
+resettare periodicamente i contatori piccoli e trasferire il conteggio sui contatori
+lunghi.
+`Ogni b accessi scelgo un contatore corto, sommo il valore al corrispondente contatore
+lungo e resetto il contatore corto`
+Quale contatore scelgo? __largest count first__
+`Copio per primo il contatore corto che ha il valore più grande, perchè è il più
+vicino all'overflow`
+
+c deve essere circa log2log2b*N (N=numero contatori*)
+Quel valore garantisce che usando l'algoritmo largest count first, non si ha mai overflow.
+Il problema dell'algoritmo lcf è che trovare il massimo impiega tempo lineare.
+Sarebbe possibile tenere memorizzato l'indice e il valore del contatore più grande,
+ma questo vale finchè non viene resettato.
+
+__Algoritmo semplificato__
+- Sia cj il contatore con il valore massimo aggiornato nel ciclo precedente di b accessi
+- Se cj >= b aggiorna e resetta cj.
+- Altrimenti aggiorna e resetta un contatore a caso perchè valga almeno b
+
+__Conteggio randomizzato__
+All'arrivo di un pacchetto aggiorna il relativo contatore con probabilità 1/c
+Mettere l'intervallo di campionamento a distanza casuale riduce il rischio di *aliasing*, 
+Cioè la sincronizzazione dell' osservazione con i fenomeni (esempio zebra nella gabbia)
+`Se un contatore vale x allora il valore atteso del numero di pacchetti è x*c`
+La *deviazione standard* è pari a qualche c
+- Se x >> c alta precisione
+- Se x ~~ c contatore inutile
+In particolare la misura degli eventi occasionali è totalmente trascurabile,
+Voglio evitare che nella misurazione si confondano eventi rilevanti ed eventi casuali.
+Un esempio di techica utilizzata è quella dell' __aggregazione a soglia__
+Esempio:
+```
+Si presenta un pacchetto con IDflusso = F
+ID flusso per connessione TCP = IPsrg||IPdst||proto||portsrg||portdst
+ID flusso per servizi destinazione = IPdst||proto||portdst
+
+Dall'ID del pacchetto calcolo tre funzioni di hash e inserisco i tre risultati in array diversi
+Se A1[h1(f)>T e così via per tutte le funzioni e array, allora salvo il flusso F
+Se il numero di pacchetti nel flusso F supera T allora Ai[hi(f)>T
+
+
+

+ 45 - 0
Piattaforme Software per la Rete/MOD1/lesson_12.md

@@ -0,0 +1,45 @@
+# Piattaforme e Software per la rete - lezione 12
+#### Giacomo Verticale
+###### 22 April 2016
+## Schema identificativo a soglia
+L'ideale sarebbe avere una batteria di contatori, uno
+per ogni identificatore di flusso, e potrei avere un blocco
+che estrae gli id dei flussi sopra la soglia, però questa
+soluzione è inefficiente.
+
+Una soluzione migliore è un insieme di vettori riempiti da funzioni di hash
+
+### Esercizio
+Suppondendo di avere un link con capacità C=100Mbit/s e N=100'000 flussi
+contemporanei (1 pacchetto alla volta, tdm statistico), finestra di misura =1s
+__Output__: elenco flussi che superano 1% di C
+Scelte di progetto: 4 array, ogni array di 1000 elementi
+
+Calcolare la probabilità che flusso da 100kbit/s sia inserito nell'elenco
+
+Il caso peggiore dell'architettura a bucket è quando ho pochi flussi molto pieni
+e i restanti quasi vuoti, se il flusso va a finire in uno dei bucket pieni, ho un 
+falso positivo.
+Se il livello di riempimento dei bucket è uniforme, ho una bassa probabilità di 
+avere un falso positivo
+La probabilità massima di falso positivo la ho quando ho tanti flussi piccoli in 
+pochi bucket, perchè questi faranno scattare la soglia.
+x=(N-1)/900kbit = 111 bucket p.falso positivo = 11,1% (risultato su un array)
+falso positivo con 4 array 0 (11,1%)^4
+
+### Contare i flussi
+Per ogni pacchetto calcolare F(flowID)
+Calcolare H = hash(F) perchè flowID in se non è uniformemente distribuito
+Contiamo il numero di 0 consecutivi del bit meno significativo
+Chiamiamo x il numero massimo di 0 osservati consecutivi
+Lo stimatore di N numero flussi distinti è N=2^x
+
+## Campionamento delle traiettorie
+Può essere utile effettuare il consistent hashing, che consiste nel fare in modo
+che tutti i nodi della rete campionino gli stessi pacchetti e ignorino gli stessi.
+Il primo nodo che campiona un pacchetto scegliendono a caso utilizza una *firma*
+del pacchetto, usando una concatenazione dei campi del pacchetto (che non cambiano
+da nodo a nodo) in modo da ottenere un valore specifico di quel pacchetto.
+
+
+

+ 102 - 0
Piattaforme Software per la Rete/MOD1/lesson_13.md

@@ -0,0 +1,102 @@
+# Piattaforme e Software per la rete - lezione 13
+#### Giacomo Verticale
+###### 29 April 2016
+## Ingegneria del traffico
+- Ingegneria del traffico IP
+    - Consiste nell-agire sui pesi dei protocolli di routing
+    - Ha delle limitazioni
+- Ingegneria del traffico con __MPLS__
+    - Consente instradamento puntuale di
+         - singoli flussi
+         - classi di traffico (aggregati di flussi)
+
+Vedendo la pila protocollare le soluzioni di ingegneria del
+traffico come MPLS si posizionano tra Data Link e IP
+Perché agiscono prima che IP effettui il routing.
+
+|L2 Header|
+| --- | 
+|...|
+|...|
+|IP Header|
+
+Tra gli header L2 e Gli header IP vengono inserite delle etichette
+Nell'header L2 é indicato nel campo *data type* che il payload é __MPLS__
+L'ultima etichetta é contrassegnata con 1 nel capo *S* in modo da sapere
+che la parola successiva é il pacchetto IP e non un ulteriore etichetta.
+
+### Campi dell'intestazione MPLS
+- etichetta = indirizzo preso da uno spazio di flat
+- exp = usato analogamente a *type of service*, ad
+esempio per classificare i pacchetti in modo da
+garantire la loro consegna.
+- S = é posto a uno nell'utlima etichetta
+- TTL = come in IP.
+
+__MPLS__= Multi Protocol Label Switching
+Di protocolli di livello 3 é usato praticamente solo IP
+mentre Puó lavorare su tutti i protocolli di livello 2 
+su cui puó lavorare IP.
+
+MPLS si trova su alcuni segmenti di reti, generalmente appartenenti 
+ad un solo gestore.
+Dei nodi equipaggiati con MPLS nella rete ce ne sono alcuni
+presenti al confine della rete ed altri al bordo.
+I nodi fanno un po' da switch e un po' da router IP
+I nodi al bordo vengono chiamati __Label Edge Router__
+Quelli in mezzo vengono chiamati __Label Switching Router__
+
+Gli __LER__:
+- Classificano pacchetti IP
+- Applicano una etichetta
+- inoltra
+
+Gli __LSR__:
+- Instraddano i pacchetti sulla base delle etichette.
+
+Questo tipo di soluzioni viene utilizzato in reti metropolitane
+per far fare percorsi diversi a tipi diversi di traffico
+
+Operazioni di un __LER__:
+- Push = aggiunge un layer di etichetta
+- Pop = rimuove l'etichetta esterna
+
+Operazioni di un __LSR__:
+- swap = modificare il valore dell'etichetta esterna.
+Il valore numerico dell'etichetta viene cambiato perché in questo modo 
+é necessario mettere d'accordo sul valore di un etichetta solo pochi nodi
+e non tutti i nodi.
+In questo modo é possibile anche avere piú reti __MPLS__ innestate una
+nell'altra.
+
+__FEC__ = Forwarding Equivalence Class, indica che i pacchetti
+appartenenti ad una sola classe vengono gestiti e inoltrati in modo uniforme.
+
+|FEC|Etichetta locale| Etichette remote|
+|---|---|
+|Regola 1 | 29|R1:45 R2:50|
+|Regola 2 | ||
+
+Viene espressa in una tabella in cui si esprime la corrispondenza
+tra etichette locali ed etichette remote.
+Tuttavia la tabella completa viene distribuita nei vari nodi in cui é presente 
+o solo la colonna *etichetta locale* o quella *etichette remote*
+Quindi non costruisco un insieme di circuiti virtuali ma un insieme
+di *cammini* che sono *unidirezionali*
+
+## Ingegneria del traffico
+Per realizzare l´ architettura necessaria devo:
+- Definire flussi e classi di traffico
+    - I __LER__ associano i pacchetti alle FEC usando un classificatore
+- Descrivere ogni classe di traffico.
+    - Deve essere data (per esempio la banda di picco).
+- Descrizione della rete e della disponibilitá di risorse
+    - Non basta la mappa fornita da link state, serve la banda disponibile.
+    - In internet viene esteso OSPF (OSPF-TE)che comunica anche disponibilitá di banda.
+- Implementare un algoritmo che decida dove instradare i vari flussi.
+    - Puó essere lento e trovare l'ottimo assoluto o veloce e venire eseguito spesso
+- Protocollo per inserire i percorsi nelle tabelle.
+    - IETF cosniglia RSVP-TE
+
+
+

+ 143 - 0
Piattaforme Software per la Rete/MOD1/lesson_14.md

@@ -0,0 +1,143 @@
+# Piattaforme e Software per la rete - lezione 14
+#### Giacomo Verticale
+###### 10 May 2016
+## Software Defined Networking con Openflow
+
+In una SDN sono presenti due flussi,
+Verso la forwarding table vanno i *pacchetti utente*
+Verso il controller vanno i *pacchetti di controllo*
+
+La parte di controllo consiste in una __RIB__ ovvero Routing Information Base
+
+Dallo switch contenente la forwarding table, i pacchetti vengono inviati 
+alla tabella dello switch, che comunica con il controllore.
+
+L'interfaccia dal controllore al campo (insieme di nodi che gestiscono i pacchetti)
+viene chiamata __southbound__
+Per gli switch abbiamo una quasi __commoditizzazione__ dovuta dal fatto
+che i diversi switch hanno caratteristiche simili e prezzo simile che varia in base al
+costo dei pezzi utilizzati.
+I controllori invece essendo oggetti monolitici, si differenziano molto in base al vendor
+e l'interfaccia __northbound__ (interfaccia di controllo del controllore) varia in base al
+marchio.
+
+Se adotto un controllore per switch la rete ha una resistenza ai guasti
+Se invece avessi un controllore unico, la funzionalitá della rete dipende da quel singolo nodo.
+
+La pratica adottata é utilizzare piú controllori per vari switch, che comunicano tra di
+loro tramite l'interfaccia __east-west__.
+
+Anche per questa interfaccia ci sono diverse soluzioni in base al vendor, ma 
+presumendo che una rete venga composta da controllori della stessa marca, 
+il protocollo proprietario tra due controllori funziona.
+
+## Il protocollo OpenFlow (southbound)
+Il protocollo openflow é uno standard, non IEEE, non IETF, open non sta per open source
+ma per il fatto che chiunque puó usare lo standard senza pagare royalties.
+Esso definisce:
+- Modello astratto di switch
+- Azioni che il controllore puó compiere sullo switch
+- Protocollo
+
+La versione a cui facciamo riferimento é la `V.1.3 (2012)`, la V1.0 prevedeva un unica tabella
+di packet classification
+La versione attuale V.1.5 (2015) presenta nuove funzionalitá interessanti ma sono ancora troppo
+recenti per essere adottate dai vari prodotti.
+
+### Modello dello switch
+I pacchetti entrano dalle porte di ingresso e finiscono in una pipeline
+Pipeline:
+- Flow Table:
+    - Table 0
+    - Table 1
+    - ...
+    - Table N
+
+Le __Flow Table__ sono tabelle che fanno il match sui pacchetti e possono eseguire delle azioni.
+Il pacchetto che arriva porta con se un __action set__ inizialmente vuoto.
+La tabella, per ogni pacchetto puó aggiungere delle azioni all'action set di quest'ultimo.
+La tabella ha come input per ogni pacchetto:
+- Pacchetto
+- Porta di ingresso
+- Action set
+La tabella ha come output:
+- Pacchetto
+- Porta
+- Metadati
+- Action set
+
+Le istruzioni possono consistere in "saltare ad una tabella m" o saltare all'uscita.
+All'uscita vengono eseguite tutte le azioni presenti nell'action set.
+
+Inoltre é presente il client openflow e una group table
+La group table contiene dei cambiamenti da applicare globalmente a tutti i flussi del gruppo.
+
+Se un pacchetto non effettua il match su nessuna riga, viene attivata una regola di default se presente,
+altrimenti il pacchetto va scartato.
+
+Le __porte fisiche__ (per INPUT e OUTPUT) 
+Le __porte logiche__ (per INPUT e OUTPUT) sono differenti dalle porte fisiche
+per il fatto che una singola porta fisica puó essere divisa in piú porte logiche per la gestione di diversi flussi.
+
+Tipicamente con una tipologia a stella voglio comunicare tra due estremi senza passare per il centro
+e per questo posso usare dei protocolli speciali di livello 2.
+
+Spesso per aumentare la velocitá di collegamento tra due link conviene usare piú collegamenti
+fisici piuttosto che comprarne uno di capacitá superiore.
+Normalmente lo spanning-tree spegnerebbe tre delle 4 porte ma posso aggregare i link in modo che lo switch
+li veda come un unico collegamento ed evito problemi di loop.
+
+Le __porte all__ (solo OUTPUT) che copiano il pacchetto su tutte le uscite (tranne la porta di ingresso), 
+questo implementa il broadcast ethernet.
+
+La __porta controller__ (per input o output), che incapsula il pacchetto nel protocollo openflow
+e lo spedisce al controller.
+
+La __porta any__ Usata solo nei match
+
+La __porta local__ Usata solo se lo swtich viene collegato come un host,
+ovvero reindirizza il pacchetto ai livelli superiori dell'host su cui é implementato lo switch.
+
+## Flow Table
+é presente all'interno della pipeline
+é una lista di tante *flow entry*
+
+Match fields | Prioritá | Contatori| Istruzioni | Timeout | Cookie 
+---|---|---|---|---|---
+
+I match fields possono essere:
+- Porta ingresso
+- Campi pacchetto
+- Metadati (da una tabella all'altra)
+
+Questi match possono solo essere esatti (o wildcard) 
+Quindi non possono essere implementate tabelle di routing IP.
+La prioritá determina a paritá di match quale regola si attiverá.
+I timeout servono per far scadere le regole
+Possono essere:
+- Hard timeout: la regola rimane attiva per il periodo indicato
+- Idle timeout: il timeout viene resettato quando la regola effettua un match.
+
+Il cookie é un identificativo scelto univocamente per la regola.
+Servono per indicare una specifica regola nei comandi openflow.
+
+## Gestione di un pacchetto
+- Arriva pacchetto
+- Inizia da tabella n=0
+- Match tabella n?
+    - No: esiste riga default (table miss)?
+        - No: DROP
+        - Si: eseguo azione (vedi match:si)
+    - Si: Aggiorno contatori, reset timer, esegui istruzioni
+        - Aggiorna action set
+        - Esegui azioni immediate
+        - Aggiorna metadati
+        - Esiste istruzione GOTO?
+            - No: esegui action set
+            - Si: eseguo match con n della GOTO
+
+La tabella con indice massimo non puó avere istruzione GOTO, questo garantisce che il pipeline finisca
+per ogni pacchetto.
+
+
+

+ 144 - 0
Piattaforme Software per la Rete/MOD1/lesson_15.md

@@ -0,0 +1,144 @@
+# Piattaforme e Software per la rete - lezione 15
+#### Giacomo Verticale
+###### 24 May 2016
+## BGP - Border Gateway Protocol
+I due protocolli piú complessi di internet che tengono in piedi la rete sono
+TCP e BGP.
+Permette di esprimere delle esigenze di collegamento degli operatori
+di tipo economico e non solo di ottimalitá del percorso.
+
+### Scopo
+> Comunicare informazioni sulle reti
+Per IPv4 rete=a.b.c.d/n
+Da quando non esiste piú l'indirizzamento a classi,
+si usa il termine rete per indicare un blocco di indirizzi,
+a prescindere che questo corrisponda ad una rete fisica o meno.
+
+agisce 
+- tra Sistemi autonomi (AS) - __eBGP__ (BGP esterno)
+- entro un sistema autonomo - __iBGP__ (BGP interno)
+
+### Architettura di internet
+Un insieme di reti forma un __sistema autonomo__
+é un insieme di reti gestiti dalla stessa entitá organizzativa
+o piú specificatamente, un insieme di reti in cui il routing
+viene effettuato in modo uniforme.
+Protocolli di routing interni:
+- RIP
+- OSPF
+Distribuiscono all'interno della rete le informazioni sulla raggiungibilitá.
+
+Un approccio di questo tipo non scala per reti molto grandi perché:
+- Diverse reti magari concorrenti non vogliono diffondere informaizoni
+sulla topologia interna
+
+I sistemi autonomi comunicano tra di loro tramite il protocollo eBGP.
+Le informazioni vengono propagate da un sistema autonomo verso i propri vicini e cosí via.
+
+Un informazione BGP comprende tutti i sistemi autonomi da attraversare per raggiungere 
+una destinazione, non vengono fornite informazioni sul routing all'interno del 
+sistema autonomo.
+Le Informazioni BGP vengono comunicate all´ interno dell'autonomous system tramite iBGP.
+
+__Come fa a funzionare BGP se esso stesso serve al routing__
+- eBGP funziona solo tra nodi next-hop collegati a livello 2,
+quindi non servono particolari informazioni di routing.
+- iBGP lavora all'interno del sistema autonomo dove sono giá presenti informazioni
+di routing, fornite ad esempio da OSPF.
+
+__Fasi del routing completo__
+- Protocolli interni (OSPF,RIP) effettuano il routing interno
+- iBGP si instaura sul sistema autonomo
+- eBGP propaga le informazioni tra sistemi autonomi.
+
+BGP usa TCP, e ne ricava una indicazione di affidabilitá del percorso:
+Se la connessione TCP non é in piedi, il percorso non é disponibile.
+
+BGP usa un approccio DV_like (distance vector) chiamato __path vector__
+ perché sarebbe complicato distribuire informazioni su miliardi di nodi
+e alcuni agenti non vogliono distribuire informazioni sulla topologia di rete.
+A differenza del distance vector vengono inviate informazioni
+sulla lista di sistemi autonomi da attraversare per raggiungere la destinazione.
+
+### Esempio di comunicazione BGP
+Destinazione | S.A. da attraversare
+---|---
+N1 | {R1,ASx,ASy,..}
+N2 | router di entrata nell'AS
+
+costo rotta = n' AS attraversati
+Il costo di attraversameto di un sistema autonomo é cosí alto che si contano
+solo i sistemi autonomi attraversati.
+
+Per scoraggiare un percorso, il sistema autonomo puó inserire se stesso piú volte
+nella lista, in modo che il percorso risulti piú lungo (usato per rotte di backup
+magari tariffate a consumo)
+
+### Messaggi BGP
+Esistono messaggi chiave e messaggi opzionali che possono essere implementati o meno
+
+- OPEN - __apre sessione__: viene dichiarato il numero del sistema autonomo, e se i numeri
+dei due interlocutori sono uguali si usa BGP interno, altrimenti esterno
+- UPDATE - __propaga o ritira informazioni su un prefisso__: viene usato per 
+distribuire informazioni sulle rotte.
+- KEEPALIVE - __verifica raggiungibilitá dell'host__: TCP non é in grado di capire 
+se l'host remoto é ancora vivo, questa cosa viene lasciata al protocollo applicativo.
+- NOTIFICATION - __chiude la sessione__: Notifica che l'entitá sta andando in 
+*mainteinance*
+- ROUTE REFRESH...
+
+Nel momento in cui un BGP speaker (router che usa BGP) riceve un update, deve 
+ridistribuirlo ai suoi vicini, e questo avviene in modo differente tra eBGP e iBGP.
+Una funzionalitá importante di BGP sono le politiche di __filtering__ che permettono 
+di distribuire in modo selettivo o non distribuire alcune informazioni.
+__Regole__:
+- regola 0: Quando si redistribuisce con eBGP si aggiunge in testa al percorso
+il proprio _numero di AS_.
+- regola 1: 
+    1. Si redistribuiscono via iBGP i percorsi ottenuti tramite eBGP
+    2. Si redistribuiscono via eBGP i percorsi ottenuti tramite iBGP
+- regola 2: Non si redistribuiscono via iBGP i percorsi ottenuti tramite iBGP
+(evita che un router riceva un informazione piú volte).
+Questo implica che tutti i router di un A.S siano connessi a maglia completa,
+altrimenti il pacchetto non raggiungerebbe tutti i router.
+ 
+### Path attributes
+Vengono propagati insieme all'annuncio
+
+__Struttura annuncio__
+
+Prefisso | contenuto
+---|---
+PATH | lista di AS + router di entrata
+ATTRIBUTI | ...
+
+__Path attributes__
+- ORIGIN:
+    - IGP: inserito da un IGP (Gateway = vecchio nome dei router)
+    - EGP: inserito da EGP (non usato piú da anni)
+    - incompleto: inserito a mano
+- AS-PATH
+- NEXT-HOP
+- MULTI-EXIT DISCRIMINATOR (solo in eBGP): esprime la preferenza di inviare pacchetti
+nella strada con MED piú basso.
+- LOCAL PREF (solo in iBGP): é l'analogo del MED internamente al S.A. permette di 
+usare il link tra A.S che si preferisce (LOCAL PREF piú alta).
+
+I pacchetti seguono il percorso inverso dell'annuncio, perché questo consiste 
+nella disponibilitá a ricevere pacchetti entranti.
+
+### BGP speaker
+- Adjacent RIB-IN: Memorizza i dati in una tabella diversa per interlocutore, 
+(memorizza tutte le informazioni ricevute, non é la tabella di routing,
+ ad esempio puó contenere doppioni).
+- Import: esegue filtraggi specificati dall'amministratore
+- Route selection.
+- Tabella di routing.
+- Export (filtrano le informazioni da propagare)
+- RIB-OUT
+
+Filtri di export usati ad esempio per accordi di *peering* che sono gratuiti e permettono
+a due ISP di scambiarsi i pacchetti diretti per l'altro ma non quelli diretti a terzi.
+
+
+

+ 120 - 0
Piattaforme Software per la Rete/MOD1/lesson_16.md

@@ -0,0 +1,120 @@
+# Piattaforme e Software per la rete - lezione 16
+#### Giacomo Verticale
+###### 27 May 2016
+## BGP Decision Process
+1. Ricezione update dai vicini (inserimento in *ADJ-RIB-IN*)
+2. Applicazione filtri import
+3. Scelta del percorso migiore (inserimento in *LOC-RIB*)
+4. Per ogni vicino: 
+    - aggregazione delle rotte, 
+    - applicazione filtri export, 
+    - inserimento in ADJ-RIB-OUT
+5. Invio UPDATE
+### Algoritmo per la scelta del percorso migliore:
+Questo algoritmo non ha nessuna garanzia di convergenza, quindi risulta necessario
+garantire la presenza di un amministratore 24/7 per sistemare eventuali problemi.
+
+1. Massima LOCAL-PREF
+2. Scegli percorsi originati localmente
+3. AS_PATH piú corto
+4. minima ORIGIN (IGP < EGP < INCOMPLETE)
+5. minimo MED
+6. Preferisci eBGP su iBGP
+7. Minimo costo verso il NEXT-HOP
+8. Se i percorsi sono tutti esterni, tieni il piú vecchio
+9. Scelgo il percorso annunciato dal router con ID minimo
+(potrei scegliere a caso, scelta deterministica per evitare route-flapping)
+(ID ROUTER = Indirizzo IP piú grande)
+
+### Relazioni di organizzazione di internet
+Fino a qualche anno fa le relazioni tra A.S. erano del tipo
+- customer/provider in cui un A.S paga un altro per risolvere le connessioni
+- peering in cui si scambiano traffico proveniente dai sottoalberi
+(ultimamente si é parlato di peering a pagamento per A.S. di dimensioni diverse
+
+I seguenti non sono standard ma best practice
+Tipo di A.S. | Preferenza | Export Filter
+--- | --- | ---
+Customer | Massima prioritá | Inviato a tutti gli A.S. vicini
+Peer | Media | Inviato a tutti gli A.S. customer
+Provider | Minima | Inviato a tutti gli A.S. customer
+
+__Teorema__
+> Se tutte le regole di filtraggio sono in accordo con le regole della tabella,
+> allora il routing é stabile (non succede *route flapping*)
+
+Da qualche anno a questa parte il classico schema gerarchico (Tier 1/2/3) é stato
+cambiato dall'introduzione di __Content Provider__ che generano una grande quantitá
+di traffico, ed effettuano accordi di peering a vari livelli permettendo 
+ai provider di avere latenze piú basse e bandwidth maggiori.
+
+Un esempio di __Content provider__ sono Netflix, Google, YouTube... perché generano 
+traffico, ad esempio Netflix negli stati uniti genera il 45% di traffico usato.
+
+Akamai invece é un __Content Delivery__ service, cioé non genera contenuto ma
+si occupa di fare accordi per distribuirlo.
+
+Questo si inserisce nel discorso sulla __net neutrality__ per cui ci si chiede
+se i contenuti dei content provider vengono trattati alla pari del traffico generato
+da altri customer.
+
+## Esercizio su OpenFlow
+- Uno switch S1
+- Tre host h1,h2,h3
+
+MAC h1=00:00...:01
+IP h1=10.0.0.1
+
+Funzione che gestisce event switch features:
+```
+...
+match = parser.OFPMatch()
+actions = [ parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,ofproto.OFPCML_NO_BUFFER)]
+...
+invia flowmod a s1 con prioritá 0
+```
+```
+match = parser.OFPmatch(eth_dst="00...3")
+actions = [parser.OFPAction Output(3)]
+invia flowmod con prioritá 1
+...
+match = parser.OFPmatch(eth_type=0x800,ip_dst="10.0.0.3")
+actions = [output 3]
+invia flowmod con prioritá 2
+```
+
+Il gestore della packet-in da un comando packet-out in flooding.
+
+__Domande:__ 
+- simulare:
+    - h1 ping h2, 
+    - h1 ping h3,
+    - apertura connessione TCP da h2 a h3 (porte 123,80)
+
+__Switch__
+ 
+Prioritá | Match | Azione | Pkt counter
+--- | --- | --- | ---
+0 | * | output controller | 0
+1 | eth_dst=0...3 | output 3 | 0
+2 | eth_type=0x080 IP_dst=IP3 | - | - 
+
+__h1 ping h2__
+- *h1->s1*: MAC 1, MAC BROADCAST, ETHTYPE=ARP, IP 1, IP 2
+- *s1->C*: (OF)PACKET_IN (pacchetto precedente)
+- *C->s1*: (OF)PACKET_OUT(stesso pacchetto, action output=FLOOD)
+- *s1->h2*:
+- *s1->h3*:
+- *h2->s1*: MAC 2, MAC 1, ETHTYPE=ARP, IP 2, IP 1
+- *s1->C*: PKT_IN(...)
+- *C->s1*: PKT_OUT(...)
+- *s1->h3*:
+- *s1->h1*: 
+- *h1->s1*: MAC 1, MAC 2, IPv4, IP 1, IP 2, ICMP
+- *s1->C*:
+- *C->s1*:
+- *s1->h2*:(...)
+- *s1->h3*:(...)
+
+
+

+ 87 - 0
Piattaforme Software per la Rete/MOD1/lesson_17.md

@@ -0,0 +1,87 @@
+# Piattaforme e Software per la rete - lezione 17
+#### Giacomo Verticale
+###### 31 May 2016
+
+# Esercizio OpenFlow
+
+__Switch__
+Prio | Match | Action
+--- | --- | ---
+0 | * | out controller
+1 | eth_dst=MAC3 | out 3
+2 | eth_type=IPv4 ip_dst=IP 3 | out
+
+__Packets__
+- h1 ping h2
+- h1 ping h3
+- h2 apre conn TCP verso h3
+
+__Hyp: tabelle ARP giá piene__
+- h2 -> s1 MAC2, MAC3, IPv4(0x0800), IP2, IP3, TCP(6)
+Il pacchetto viene ricevuto dal controllore che controlla sulla tabella, 
+il pacchetto fa match sulla terza riga perché ha prioritá piú alta.
+- s1 -> h3 ...
+- h3 -> s1 MAC3, MAC2, IPv4, IP3, IP2, TCP, 80, 123, SYN ACK
+- s1 -> C packet_in (...) / c -> s1 packet_out (...), action out flood.
+- s1 -> h1, h2...
+
+# Esercizio 2 OpenFlow
+__Topologia__
+h2,h1 - s1 - s2 - h3,h4
+
+__Event OFP Switch Features__
+```
+match su *
+actions = [output su controller]
+priority = 0
+FLOW MOD(datapath, priority, match, ...)
+```
+Datapath é sinonimo di switch, anche se uno switch puó contenere
+piú datapath e agire come piú switch in uno solo.
+Questo é un table miss perché fa match su ogni cosa e ha prioritá 0
+
+```
+match su eth_dst="FF:FF:....:FF"
+actions = [output su flood]
+FLOW MOD(datapath, priority=1, ...)
+```
+
+__Event OFP Packet In__
+Questa funzione serve a recuperare i metadati come la porta in ingresso.
+Se il match non venisse trovato, alla variabile viene assegnato `none`
+```
+in_port = msg.match ['in_port']
+pkt = packet.Packet(data = msg data)
+if len(pkt.protocols)>=2 and is instance (pkt.protocols[1], IPv4):
+    if datapath.id == 1 and pkt_ipv4.dst == '10.0.0.3':
+        match = OFPMatch(eth_src = eth.src, eth_dst=eth.dst,
+                         eth_type = IPv4, ip_dst = '10.0.0.3')
+        actions = [ OFPAction.SetField(ip_dst='10.0.0.2'),
+                    OFPAction Output(2) ]
+        FLOWMOD(match, priority=1, ...)
+else packet_out(FLOOD)
+```
+La porta in ingresso serve per effettuare il flooding di un pacchetto 
+proveniente dal controllore, senza rimandarlo nella porta di ingresso.
+
+- da h1 ad h3 pacchetto UDP 53
+- da h3 ad h2 apertura di connessione TCP/80
+
+__Tabella s1__
+0 | * | controller
+--- | --- | ---
+1 | eth_dst=FF:FF...:FF | output FLOOD
+__Tabella s2__
+0 | * | controller
+--- | --- | ---
+1 | eth_dst=FF:FF...:FF | output FLOOD
+
+ARP prepopolata
+- h1 -> s1: MAC1, MAC3, IPv4, IP1, IP3, UDP, 1234, 53
+- s1 -> C: packet_in(...)
+- C -> s1:flow_mod (match(eth_src=MAC1, eth_dst=MAC3, eth_type=IPv4,
+                    ip_dst='10.0.0.3'), priority=1,
+                    actions (set_field(ip.dst='10.0.0.2'), output(2)))
+
+
+

+ 103 - 0
Piattaforme Software per la Rete/MOD1/lesson_18.md

@@ -0,0 +1,103 @@
+# Piattaforme e Software per la rete - lezione 18
+#### Giacomo Verticale
+###### 7 June 2016
+
+# Intrusion Detection Systems
+Un IDS é un *middlebox* che si occupa di rilevare la presenza di intrusioni o 
+si assicura del rispetto delle policy di sicurezza
+In particolare i __Network Intrusion Detection Systems__ effettuano *deep packet inspection*
+Cioé analizzano il payload dei pacchetti
+
+É difficile effettuare il match a livello applicativo perché spesso i
+protocolli sono di tipo testuale, come HTTP
+
+Un __Host Intrusion Detection System__ invece si occupano di monitorare gli ingressi 
+e le uscite di un singolo host.
+
+A differenza del matching sui campi del pacchetto, il *deep packet inspection* 
+ha un rischio concredo di *falsi positivi*, ad esempio cercando una
+stringa `HTTP` nel pacchetto, potremmo rilevare anche delle email contenenti dei link.
+
+In genere i sistemi di ricerca, piú estendono il campo della loro ricerca e sono aggressivi,
+e piú c'é il rischio che trovino dei falsi positivi. Per questo di solito
+Gli IDS si limitano a lanciare degli allarmi e lasciare ad un sistema di __management__ 
+lo svolgimento dell'azione.
+
+I sistemi di *deep packet inspection* sono utilizzati anche dai provider per capire che
+frazione del traffico é di natura VoIP, in modo da poter favoreggiare o ostacolare il traffico
+per favorire la telefonia tradizionale (discorso su net neutrality)
+
+Gli IDS si dividono in:
+- __Signature Detection__ hanno un database che permette di identificare particolari
+pacchetti tramite una signature, tuttavia possono identificare solo problemi noti (es. ransomware)
+- __Anomaly Detection__ definiscono una situazione standard e segnalano un allarme ogni volta che si 
+esce da una situazione normale, questi sistemi possono prevenire anche attacchi non documentati.
+
+Un __IDS__ é piú lento rispetto ad un __firewall__, perché invece che effettuare match in posizioni note,
+deve ricercare delle stringhe nel payload.
+Un firewall viene posizionato ai bordi della rete, per identificare problemi verso l'esterno,
+mentre gli IDS vengono posti all'interno della rete per monitorare il traffico all'interno.
+
+Cisco sta proponendo dei sistemi che integrano un firewall che agisce fino al livello applicativo,
+con un IDS che é in grado di riconoscere le signature dei pacchetti.
+
+Per costruire le signature sono necessari esempi di intrusioni per poter costruire un database.
+Usate per questo sono le *honeynets*: reti che hanno l'unico scopo di attirare attacchi
+per poterli catalogare, un principio simile é usato nei sistemi antispam, in cui viene creato
+un indirizzo email che non corrisponde a nessuna persona fisica, e tutte le mail che riceve
+sono per definizione spam.
+
+## Cercare nei pacchetti
+Di solito gli IDS effettuano ricerca di stringhe nel payload, ma possono utilizzare anche 
+delle *regular expression*, anche se il costo computazionale sale.
+
+Spesso il payload di una sessione TCP é diviso tra diversi pacchetti, quindi puó essere
+effettuata una operazione di *preprocessing* che consiste nel raccogliere tutti i payload
+di una stessa connessione TCP.
+
+Un attaccante puó dividere il payload di attacco in tanti pacchetti piú piccoli, per fare
+in modo che IDS che analizzano pacchetti singoli non riescano a rilevare l'attacco
+
+Un prodotto commerciale diffuso per DPI é __SNORT__ che é un software commerciale
+di cui l'engine é open source, il database degli attacchi é disponibile a pagamento
+per le versioni piú aggiornate e gratuitamente per le versioni piú vecchie.
+
+SNORT effettua un match con un set di regole BGP
+Una volta che viene effettuato un match, viene lanciato un allarme e il pacchetto 
+viene inviato ad un supervisore o ad un sistema di management centralizzato che gestisce piú IDS,
+oppure ad un supervisore che controllerá il pacchetto.
+
+I protocolli si dividono in __binari__ e __testuali__, nei protocolli OSI sono sempre
+stati usati protocolli binari, mentre i protocolli testuali sono stati scelti da IETF
+per facilitá di debug.
+Ultimamente c'é una tendenza a usare protocolli binari perché usano meno spazio
+e bastano programmi piú semplici per leggerli, ad esempio HTTP:2.0 é un protocollo binario.
+
+Questo vantaggio é anche dovuto alla diffusione di sistemi embedded e di sensori
+che non hanno la possibilitá di far girare grossi programmi.
+Inoltre la possibilitá di debugging testuale é impedita dall'uso di protocolli crittografati,
+quindi c'é un motivo in meno per usare protocolli testuali.
+
+Nel caso di protocolli cifrati di solito viene terminata la cifratura nel sistema di DPI e la connessione
+viene continuata il chiaro verso il destinatario o viene cifrata con una chiave diversa.
+
+## Azioni possibili
+- Alert
+- Log
+- Drop
+- Reject
+
+## Regole
+Nelle regole é possibile anche effettuare delle negazioni, questo comporta un costo computazionale piú alto
+col vantaggio di ottenere un ruleset piú compatto.
+
+La parte piú interessante di queste regole é l'analisi del payload, ad esempio il campo `content` permette di 
+cercare una stringa nel payload, tuttavia l'algoritmo per fare questo ha costo lineare con la lunghezza
+del payload, e al massimo é possibile confrontare piú match allo stesso momento con un costo
+lineare non grosso, (sublineare per il numero di stringhe da cercare usando i trie).
+
+Per evitare costo computazionale inutile, i pacchetti delle connessioni che sono state accettate non
+vengono piú analizzati.
+
+
+

+ 6 - 0
Piattaforme Software per la Rete/MOD2/genpdf.sh

@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+
+# Packages needed:
+# pandoc, texlive-core, texlive-latexextra 
+
+cat lesson_*.md | pandoc --latex-engine=xelatex -o course.pdf

+ 13 - 0
Piattaforme Software per la Rete/MOD2/lesson_00.md

@@ -0,0 +1,13 @@
+---
+fontsize: 12pt
+---  
+
+# Piattaforme Software per la Rete
+
+### Modulo 2
+    
+# William Fornaciari
+
+\pagebreak
+
+

+ 114 - 0
Piattaforme Software per la Rete/MOD2/lesson_01.md

@@ -0,0 +1,114 @@
+# Piattaforme e Software per la rete
+#### William Fornaciari
+###### 9 March 2016
+## Modulo 2
+__Networking__ -> __embedded systems__ -> __Network embedded systems__
+
+## Testi adottati
+Deitel, Choffines - Operating Systems, per ripassare
+
+Mitchell Oldhamm, ... Advanced Linux Programming, scaricabile gratis.
+
+## RIpasso - Architettura di un sistema linux
+Modalità
+- Modo kernel
+- Modo utente
+    - Programmi utente
+    - Shell
+
+Hardware recente è in grado di supportare il parallelismo, 
+mentre storicamente i sistemi operativi sono pensati per la 
+condivisione delle risorse di un solo processore.
+
+Il cambiamento storico è stato dal vax780 che ha introdotto un SoC,
+- Inizialmente si è adottato un singolo core sempre più potente, fino a 2,5GHz
+- Raggiunto il limite della frequenza di clock (power wall) si cerca di aumentare le prestazioni
+aumentando il numero di core.
+
+E poi c'è il *dark silicon*
+
+Anche per quello l'evoluzione sta al momento nel creare meccanismi di memoria e di caching 
+in grado di permettere il funzionamento contemporaneo di molti core (~50)
+
+__Sistemi di gestione dinamica dele risorse__
+Come *barbecue* non gesticono i processi in modo agnostico ma danno priorità in base alle condizioni
+(es: utilizzo in batteria)
+La gestione viene fatta a livello userspace con uno strato intermedio,
+ in modo che sia indipendente dal kernel o sistema operativo.
+
+Per coordinare molti core non si usa un bus ma una Network on Chip (16 core in sù)
+
+## Funzionalità del kernel
+- Mantenere in memoria il s.o. e i programmi in spazi di indirizzamento separati 
+- Permettere il passaggio dall'esecuzione di un programma all'altro,
+ma nei sistemi a molti core la cosa è diversa (distribuzione dei thread in un pool di risorse)
+- Gestire le operazioni di I/O
+A volte nelle applicazioni embedded si scrive del codice bare-metal senza sistema operativo
+In quel caso l'I/O è gestito dal proprio software
+- Verifica dei dati di esecuzione, ad esempio in sysfs
+
+#### BoardSupportP?
+è lo strato che permette di mappare le funzioni del sistema operativo su un particolare tipo di hardware.
+
+### Esecuzione di un processo
+Il kernel sceglie il processo da mandare in esecuzione
+Quando un processo richiede un servizio di sistema tramite una SVC
+Viene fornita la funzione richiesta nel contesto del processo.
+
+### Sospensione dei processo
+Il processo può lasciare l'esecuzione
+- Per *sospensione volontaria* con cui passa allo stato di attesa 
+(Ad esempio per aspettare un evento di I/O)
+- Per *fine del quanto di tempo* 
+
+3 stati:
+- Processo in esecuzione: processo che usa il processore, tanti quanti i core
+- Processi in attesa: attende una risorsa non disponibile.
+- Processi pronti: attende di essere eseguito
+
+I processi in attesa sono differenziati da quelli pronti per evitare che un proceso singolo
+monopolizzi il processore, e faccia andare gli altri in starvation.
+
+Nei sistemi con __preemption__ si può togliere il processo in esecuzione dal processore
+Nei sistemi senza, il processo tiene il processore fino alla fine del quanto di tempo o fino a che
+si sospende volontariamente.
+
+### Gestione degli interrupt
+Le interruzioni possono essere nestate, e in quel caso non si sa quando finiranno di eseguirsi. 
+Questo può creare problemi nei sistemi embedded in cui è necessario garantire un tempo di risposta rapido.
+
+Gli interrupt possono essere __mascherabili__ quando non possono essere eseguiti altri interrupt, in 
+modo da creare una sezione atomica, non interrompibile.
+
+Ci sono interruzioni che possono essere __non mascherabili__ perchè cruciali, ad esempio spegnimento in caso di batterie scariche.
+
+### Watchdog
+Viene usato per capire se un processo è bloccato, ad esempio facendo un timer che va resettato periodicamente.
+Se il timer non viene resettato e scade, viene attivato un interrupt che accende un led ad esempio.
+Collegare il watchdog al reset del sistema non è una delle soluzioni migliori (es: applicazioni critiche)
+Il watchdog implica un hardware esterno perchè il processore in quel caso è bloccato.
+
+### Gestione del quanto di tempo
+Per il quanto di tempo viene usato uno dei timer programmabili hardware del PC (RTC)
+Facendo un quanto di tempo troppo piccolo ho un parallelismo più spinto 
+ma aumenta l'overhead per il context switching
+Il problema in questo caso è il mixed-workflow in cui è importante che il sistema rimanga interattivo
+ed è anche importante terminare i processi lunghi.
+
+### Ritorno da interrupt
+Fino a 8 anni fa il kernel linux era monolitico (non interrompibile) mentre ora è preemptable (interrompibile)
+e in questo modo è più difficile da gestire ma è più interattivo.
+
+### Memoria Virtuale (swap)
+Nei sistemi embedded non esiste, perchè serve avere un sistema predicibile.
+Anche i questo caso i processi che subiscono swap-in (ritorno in memoria da swap) finiscono 
+in uno stato in attesa, e non pronto, per evitare la starvation dei processi
+
+### Stati dei processi UNIX
+Esiste una distinzione tra Ready to run in memory e Preempted
+
+### Processo di boot
+Ultimamente in linux si sta tentando di caricare le cose non tutte insieme ma quelle essenziali prima in modo che il sistema risulti già usabile
+
+
+

+ 112 - 0
Piattaforme Software per la Rete/MOD2/lesson_02.md

@@ -0,0 +1,112 @@
+# Piattaforme e Software per la rete - lezione 2
+#### William Fornaciari
+###### 10 March 2016
+## Processi - Concetti di base
+
+### Esecuzione sequenziale (senza s.o.)
+I sistemi tradizionali adottano l'__esecuzione sequenziale__, 
+possibile adottarla su ogni core per sistemi multicore. 
+Questa soluzione presenta diversi vantaggi
+- Semplicità e facilità di debug
+- Determinismo della sequenza e dei tempi di esecuzione
+
+Ma anche degli svantaggi
+- Accesso di un solo utente alla volta
+- Esecuzione di un solo programma alla volta
+- Scarso sfruttamento delle risorse hardware
+
+### Esecuzione Parallela (con s.o.)
+Parallelismo *simulato* se ho un solo processore, *reale* se ho cpu multiple
+Introduce alcuni problemi:
+- Il determinismo non è garantito automaticamente
+- L'ordine di esecuzione non è fissato
+- Conflitti di accesso alle risorse
+Questi problemi sono risolti dal Sistema Operativo
+- Scheduling, memoria virtuale, periferiche virtuali...
+- Gestione di processi, sincronizzazione...
+
+### Processo
+Di solito i processi vengono eseguiti su un sistema operativo.
+Ma è possibile eseguire degli scheduler direttamente sul ferro
+ e far eseguire agli scheduler il proprio processo (es: rtx)
+vedi esecuzione sequenziale
+
+#### Nota
+I processori per sistemi embedded (es: STM32) costano da qualche centesimo a qualche €, e
+dispongono di una memoria di qualche KB, quindi è utile risparmiare memoria, ad es.
+ evitando di usare un sistema operativo.
+
+Ogni processo è identificato da un PID (Process IDentifier) univoco e viene creato
+da un processo *padre*
+Unica eccezione è il processo __init__ che è il primo ad essere eseguito
+
+### Gerarchia di processi
+
+Nei sistemi embedded non serve il paradigma di avvio tradizionale linux
+init -> login -> shell -> processo
+Può essere lanciato direttamente il processo principale del sistema.
+
+### Modello di memoria
+__Memoria virtuale__ viene mappata sulla memoria disica dal sistema operativo
+mediante il PD (Process Descriptor)
+Questo da più flessibilità perchè evito frammentazione in memoria, permette di far andare
+uno stesso programma su hardware diversi, di questo si occupa la MMU. 
+Nei sistemi embedded non c'è MMU e non viene usata memoria virtuale. 
+Memoria organizzata in __segmenti__ 
+
+### Operazioni sui processi
+- Creazione di un processo: 
+   - `fork()` crea una copia del processo padre con la sola eccezione del PID,
+il figlio condivide il codice del padre, ha la parde dati copiata ma ha un suo Process Descriptor.
+   - Lo spreco di memoria legato alla copia della sezione dati può essere evitato con
+una `vfork()` o una `fork()` che implementa copy on write.
+
+- Terminazione di un processo
+   - con la `exit(int status)` viene salvato il valore di stato nel Process Descriptor, 
+e viene segnalata la terminazione del figlio inviando una `SIGCHLD` al padre. 
+
+- Attendere la terminazione di un processo
+   - `wait()` Se viene eseguita prima della terminazione del ciclo viene aspettata la terminazione 
+del figlio, se viene eseguida dopo la terminazione, il figlio diventa un processo zombie.
+   - Stato di terminazione viene passato nella parte significativa per 
+stato normale `es: 0x2000`, nella parte meno significativa per codici di errore `es: 0x0009`
+è una cosa sporca ma è stata pensata tanti anni fa.
+
+- Sostituire il codice di un processo
+   - `exec()` Segmenti TEXT e DATA sostituiti ma stesso PID e file/socket aperti rimangono.
+Ci sono vari tipi di exec che sono frontend di `execve()`
+
+Esempio
+```
+if((pid2 = fork()) == 0)
+   execv("editor", argv);
+```
+
+- Segnalazione di eventi
+Un processo *orphaned* è quando il padre termina prima che termini il figlio, quando il figlio
+termina, viene adottato dal processo init (parent PID settato a 1 nel PD).
+
+### Inizializzazione e terminazione di un programma
+La funziona `_exit()` rappresenta l'ultima operazione eseguita dalla `exit()` che invece effettua
+ tutte le operazioni di housekeeping, che possono anche essere personalizzate utilizzando
+ le primitive `atexit(void(*f) (void));` e se ne possono registrare fino a 32.
+
+La terminazione di un programma avviene sempre mediante un segnale
+- Ricevuto dal processo
+- Generato dal processo tramite `abort()`, che invia un segnale a se stesso per
+ funzionare in modo analogo alla prima opzione.
+
+I segnali possono essere inviati tramite la funzione `kill()` (nome fuorviante)
+Il più delle volte la signal implica la chiusura del processo, a volte viene effettuato un core dump
+cioè un salvataggio dello stato del sistema utile per debuggare.
+Si può registrare un handler per una signal, altrimenti utilizza il comportamento di default,
+ ad esempio CTRL+C agisce da signal non registrata e quindi come effetto chiude 'applicazione. 
+La funzione `raise()` invia un segnale a processo stesso. 
+Nel caso si riceva un segnale è possibile
+- Ignorare il segnale, tranne SIGKILL e SIGSTOP es:`h = signal(SIGINT,SIG_IGN );`
+- Effettuare una operazione specificata tramite un signal handler `sighandler_t signal(int signum, sighandler_t,...)`
+`alarm()` imposta un timer che alla scadenza invierà un SIGALRM al processo,
+può essere combinata con un handler e pause per fare un timeout o altri barbatrucchi.
+
+
+

+ 101 - 0
Piattaforme Software per la Rete/MOD2/lesson_03.md

@@ -0,0 +1,101 @@
+# Piattaforme e Software per la rete - lezione 3
+#### William Fornaciari
+###### 23 March 2016
+## Cosa sono i thread
+I thread sono nati per alleggerire il parallelismo su macchine lente
+Non sempre i thread sono vantaggiosi, se usati troppo sono svantaggiosi 
+rispetto ai processi tradizionali.
+Un processo contiene
+- Risorse
+- Contesto di esecuzione
+
+I thread dello stesso processo condividono tutte le risorse aperte,
+con le dovute problematiche di concorrenza e sincronizzazione.
+Per questo sono stati introdotti i meccanismi di mutex tipici dei
+processi, anche per i thread.
+L'esempio classico sono i server, in cui posso creare tanti thread e 
+all'occorrenza risvegliarli, inoltre su sistemi multicore posso dividere
+i thread sui vari core, per gestire il carico.
+
+### Vantaggi
+L'overhead di creazione/distruzione di thread era di un fattore 10 rispetto ai
+processi nei primi sistemi linux che lo implementavano.
+
+Capostipite dei thread sono i solaris thread, che venivano usati da Solaris (girava su SPARC)
+Su windows sono venuti sfruttati bene da windows NT.
+I threads vennero introdotti da una libreria thread scritta da uno studente di Berkley
+e consistevano in una esecuzione di diverse funzioni in modo trasparente al kernel.
+
+Quindi i thread possono essere sia *kernel* che *utente*
+
+### Team model
+Utile per partizionare un applicazione
+Si utilizza un thread diverso per ogni funzione, ad esempio si dedica
+un thread alla sola interazione utente, in modo da avere una maggiore
+reattività agli input.
+
+La prima applicazione dei thread è stata un foglio elettronico,
+in cui abbiamo un thread per input, uno per video e uno per il calcolo.
+
+Non è detto che un problema si riesca a mappare bene su un'architettura multicore,
+ad esempio perchè la complessità dei thread è sbilanciata,
+es: thread input o display sono molto più leggeri del thread computing.
+__Vantaggio principale__ è dare reattività all'esperienza utente.
+
+### Architettura a dispatcher
+Un thread detto *dispatcher* riceve richieste di servizio e le invia 
+ai vari thread.
+Si mappa molto bene su architetture a cluster, in cui abbiamo un core principale(dispatcher)
+e dei worker core con memoria condivisa a cui viene inviato il lavoro.
+Questa architettura presenta dei vantaggi per il risparmio energetico
+perchè posso tenere spenti i worker core finchè non arriva del lavoro da assegnargli.
+
+### Architettura a pipeline
+Costituito da elementi con ingresso e uscita (es: bash pipe)
+In questo caso il secondo elemento ha un buffer di dati in ingresso e può elaborare
+senza dover scrivere/leggere da memoria.
+Vantaggiosa per effettuare delle ricerche, in quanto non serve elaborare 
+tutti i dati per trovare un risultato.
+
+### User thread package
+Viene implementato uno strato di supporto runtime a livello utente per gestire i thread
+Il supporto si occupa dello scheduling dei thread attivi di un processo.
+Simile a co-routine nella programmazione.
+__Difficile__ sfruttare i sistemi multicore
+__Facile__ da implementare
+
+### Kernel thread package
+Se un thread è bloccato non blocca l'intero processo come nel caso utente.
+Serve implementare delle specifiche chiamate di sistema e modificare il kernel.
+
+### Relazione tra thread e processi
+- Many-to-one: un solo processo gestisce tutti i thread
+- One-to-one: user-level thread viene mappato su kernel thread
+
+### Comunicazione e sincronizzazione
+Le principali soluzioni per far comunicare i thread sono:
+- __Semafori:__ Contatore che viene incrementato e decrementato, 
+i processi possono essere eseguiti quando è non negativo 
+- __Mutex:__ Versione binaria del semaforo
+- __Condition Variable:__ 
+- __Monitor e scambio messaggi__
+
+## Parallelismo
+*  __Processo__ realizza il concetto di macchina virutale e ha un forte *isolamento*
+* __Thread__ utile per processi leggeri, in caso di errore può far fallire gli altri 
+thread dello stesso processo o il processo stesso.
+I thread inoltre sono molto efficienti nel parallelismo e concorrenza rispetto ai processi.
+
+__Concorrenza__ nel caso di parallelismo reale può portare ad eseguire insieme i due processi
+In un sistema monoprocessore i due processi verranno eseguiti sequenzialmente ma non si sa in quale ordine
+
+__POSIX__ è un modo per standardizzare le interfacce dei sistemi operativi, per migliorare
+la *portabilità* del codice.
+
+### Scheduling for uniprocessor systems
+__RIPASSARE__
+Il carico dei processi di solito avviene a *burst*, seguiti dall'attesa per l'I/O
+Lo scheduler *preemptive* è più difficile da gestire rispetto ad uno normale
+
+
+

+ 90 - 0
Piattaforme Software per la Rete/MOD2/lesson_04.md

@@ -0,0 +1,90 @@
+# Piattaforme e Software per la rete - lezione 4
+#### William Fornaciari
+###### 30 March 2016
+## Modulo 2
+Algoritmi di scheduling divisi in:
+- Preemptive
+- Non preemptive
+
+è possibile adottare delle politiche per ottimizzare dei parametri a discapito
+della fairness dello scheduling, ad esempio posso far terminare prima processi brevi
+Ottenendo una risposta mediamente più rapida ma con un rischio di *starvation*.
+Spesso serve integrare queste politiche con altre soluzioni per ridurre questo rischio.
+Politiche:
+- Shortest Remaining Time
+Per processi periodici è di solito possibile stimare i tempi di esecuzione.
+Processi di interazione con l'utente possono avere un utilizzo di CPU variabile,
+es: algoritmi adattativi. 
+
+- Highest Response Ratio Next
+Si calcola per ogni processo 
+(Tempo di servizio stimato + tempo speso ad aspettare)/Tempo di servizio stimato
+E si sceglie il processo con il rapporto più alto, ovvero si mette in relazione 
+il tempo di attesa con la durata del processo, es: un attesa di 1 sec pesa più su un processo
+di un paio di secondi rispetto ad un processo di 5 minuti.
+
+- Feedback Scheduling
+Ho diverse code, modello ricondotto a priority queue.
+
+- Fair-Share Scheduling
+Posso raggruppare i processi e dividere il tempo della cpu tra i diversi gruppi,
+quando un certo gruppo riceve la priorità, viene divisa equamente tra i processi 
+che vi fanno parte in modo da garantire che determinate applicazioni abbiano 
+un tempo di servizio garantito.
+
+#### Prevedere la lunghezza del prossimo CPU burst
+__Media esponenziale__
+tau(n+1)=alpha t(n)+(1-alpha)tau(n)
+alpha è il peso da dare all'ultima misurazione piuttosto che alle stime precedenti.
+In particolare determina l'ampiezza della storia da prendere in considerazione.
+
+- Priority Scheduling
+Viene eseguito il processo con la priorità più alta, se la coda è vuota si passa a quelle successive.
+
+- Round Robin
+Si può dimostrare che non soffre di problemi di starvation, se do un tempo di slot molto
+grande, degenera in una FIFO in cui il processo tiene il tempo CPU finchè non termina.
+Se scelgo un tempo più piccolo il sistema sembrerà più reattivo ma aumenta l'overhead.
+Il Round Robin ha un tempo medio di turnaround > di SRT ma risulta più reattivo
+Una regola a spanne è che l'80% dei processi deve completare entro il quanto di tempo.
+
+- Multilevel Queue
+Posso dividere la coda di processi in ForeGround e BackGround e usare politiche diverse.
+
+- Multilevel Feedback Queue
+Ho code multiple di priorità, gestite all'interno in Round Robin
+La priorità dei processi viene ricalcolata periodicamente in base a Nice e una funzione dell'uso della CPU
+Così i processi che hanno usato la CPU diventa meno probabile che abbiano accesso nuovamente alla CPU.
+La __Niceness__ determina la priorità iniziale, 0 è neutra, NICE>0 diminuisce la priorità, NICE<0 l'aumenta.
+Questa politica è stata implementata per prima da BSD Unix ed è efficace.
+Scheduler a complessità costante utilizzano un meccanismo hardware che dato un elenco di bit
+uno per ogni coda, un istruzione assembler restituisce in tempo costante la posizione del primo 0.
+
+Nei sistemi embedded un modo sicuro per eseguire task mission critical/real time è allocarci uno dei vari processori
+In modo che nel caso pessimo diventa predicibile, altrimenti ci sono gli altri core per allocazione best effort.
+
+### Multi-processor Scheduling
+Nel caso di Symmetric Multiprocessing (SMP) i vari processori accedono ad una struttura dati comune
+da cui prendono i processi da eseguire.
+
+### Real-Time Scheduling
+- Real Time Hardware
+- Soft Real Time
+Il kernel preemptable è un buon contributo al Real Time computing.
+
+### Deterministic modeling
+Può essere importante fare scheduling in funzione della temperatura target della cpu o delle varie cpu
+L'analisi non sfrutta il workload reale ma contronta i vari algoritmi di scheduling verso un caso di test (benchmark)
+
+## Applicazioni distribuite
+Un applicazione distribuita può usare uno stesso cpu o più core di una sola cpu o cpu collegate via rete
+ovviamente in questo ultimo caso aumenta il ritardo per la comunicazione e i consumi.
+Di solito la comunicazione avviene tramite le API TCP/IP del sistema operativo.
+La API standard per TCP/IP si chiama "interfaccia __socket__", presentato nel 1985 al Politecnico
+da studenti di Berkley
+La API permette anche l'interoperabilità tra sistemi operativi diversi.
+
+Il protocollo più comune è quello *client/server*
+
+
+

+ 69 - 0
Piattaforme Software per la Rete/MOD2/lesson_05.md

@@ -0,0 +1,69 @@
+# Piattaforme e Software per la rete - lezione 5
+#### William Fornaciari
+###### 31 March 2016
+## Programmazione di rete parte 2
+Server di tipo
+- sequenziale: una richiesta gestita alla volta
+- parallelo: usano un pool di processi per elaborare le richieste
+
+Per la programmazione faccio una `accept(...)` che è bloccante e ritorna quando ho
+un client che comunica, a quel punto faccio la fork e gestisco il client nel figlio.
+Statisticamente risulta più comodo creare dei server fatti da piccoli multicore, 
+in quanto le richieste di un server di solito non sono intensive di calcolo ma 
+con tante richieste parallele. Per questo ultimamente vengono usati server blade che montano
+molte cpu ARM che a pari di potenza di calcolo parallelo consumano meno 9:1
+Per questo si parla di computer continuum, (es: progetto montblanc).
+
+## Inter-process Communication
+Per comunicazione tra processi su una stessa macchina si può usare shared memory
+come nel mulithtreading.
+Per comunicazione tra pocessori distanti o diversi ci sono problemi di compatibilità
+su piattaforme diverse, e java in questo caso non può essere una soluzione perchè
+non è abbastanza efficiente per sistemi emebedded.
+IPC methods
+- message passing
+- signals
+- pipes
+- message passing classico (sockets, RPC...)
+
+Come aspetti prestazionali sono diversi ma come semantica sono intercambiabili.
+Metodi di __Message Passing__ evita problemi di *memoria condivisa* nei sistemi multicore
+Di solito viene implementato prima del resto quando si realizza una nuova architettura.
+
+La __comunicazione asincrona__ a differenza di quella bloccante ha bisogno di un buffer.
+Una __comunicazione sincrona__ non ha bisogno di buffer ed è *esplicitamente sincronizzata*
+Normalmente la `send()` non è bloccante mentre la `receive()` lo è,
+in caso di comunicazione sincrona, sia `send()` che `receive()` sono bloccanti, quest'ultimo
+modo di comunicazione si chiama *rendez-vous*.
+
+#### Addressing in Message Passing
+Posso avere una destinazione esplicita per i messaggi, che però va fissata nel codice o
+scelta durante la compilazione, mentre se non si conosce il destinatario si può
+usare un meccanismo a __mailbox__ o __port__ che è la variante con un solo lettore per mailbox
+Di solito la porta viene distrutta quando il processo owner termina.
+
+#### Message Format
+Generalmente consiste in
+- Header: contiene informazioni su destinazione e controllo
+- Body o Payload: contiene i dati inviati nel messaggio.
+
+Altre soluzioni sono quelle __produttore/consumatore__
+
+### Unix Pipes
+è molto efficiente in termine di cicli macchina, presenta mutua esclusione 
+(può accederci un solo processo alla volta) il produttore è bloccato se non c'è spazio.
+Vengono gestite come dei file, con la primitiva `pipe()`
+```
+int p[2];
+if(pipe(p) == -1) print(error);
+```
+In questo modo ho due pipe, posso usare `pipe[0]` per scrivere e `pipe[1]` per leggere
+Inizialmente posso leggere e scrivere la pipe dallo stesso processo in modo __loopback__
+Posso usare le pipe per comunicare tra padre e figlio, ma devo gestirlo bene, altrimenti entrambi
+leggono e scrivono sulla stessa pipe.
+Quindi mi serve chiudere uno dei due pipe nel padre e nel figlio con `close(p[0])` o `close(p[1])`
+Rispettivamente nel padre e nel figlio o viceversa, in modo da avere una comunicazione normale.
+Una chiusura non pulita di una pipe può portare a un errore `broken pipe`.
+
+
+

+ 45 - 0
Piattaforme Software per la Rete/MOD2/lesson_06.md

@@ -0,0 +1,45 @@
+# Piattaforme e Software per la rete - lezione 6
+#### William Fornaciari
+###### 4 April 2016
+## Deadlock
+Il __deadlock__ è la condizione in cui ognuno dei due agenti aspetta le *risorse*
+dell'altro.
+Una __risorsa__ è qualunque cosa (hardware o software) a cui si può accedere
+in mutua esclusione, es: una stampante, una licenza, una memoria...
+Le risorse possono essere:
+- __Preemptable__: la risorsa può essere sospesa senza grossi problemi (es: stampante)
+- __Non Preemptable__: la risorsa non può essere sospesa (es: software ABS)
+
+Il __busy waiting__ consiste nell'aspettare la risorsa *non pronta* in modo bloccante,
+può essere comodo far svegliare il processo dal sistema operativo o da un timer, ma
+non è detto che questa funzione sia disponibile, può essere necessario implementarla
+a mano.
+
+Le condizioni per avere un deadlock sono:
+- Mutua esclusione nell'utilizzo della risorsa
+- Hold & Wait, process holding resources can request new ones.
+- No preemption, resources taken can be reseased only from the user.
+- Circular wait: must exists between processes.
+
+Approcci per risolvere i deadlock:
+- Ignore: usato in sistemi general purpose, normalmente sovradimensionati
+- Detection and recovery:
+- Prevention: Eliminare una delle 4 precondizioni dei deadlock
+- Avoidance: Algoritmi per gestire allocazione delle risorse, molto difficile.
+
+Per rompere un loop posso aprire gli archi o togliere uno dei nodi.
+
+Un __demone__ è un processo a cui viene ucciso il padre e quindi viene ereditato
+da init.
+
+Uno __spooler__ consiste in un demone che gestisce in modo esclusivo ad esempio
+una stampante, e appena gli viene inviato un file da stampare, esso lo manda in
+stampa.
+Una politica __FIFO__ per la gestione della coda di stampa è adeguata.
+
+__Distributed deadlock detection__
+Viene inviato un messaggio che contiene informazioni su risorsa attesa e chi la attende,
+se il messaggio torna al mittente con il proprio ID, allora è stato rilevato un ciclo.
+
+
+

+ 93 - 0
Piattaforme Software per la Rete/MOD2/lesson_07.md

@@ -0,0 +1,93 @@
+# Piattaforme e Software per la rete - lezione 7
+#### William Fornaciari
+###### 13 April 2016
+## Shared Memory
+Possibilità di creare un segmento di memoria condiviso per far scambiare
+i dati tra diversi processi.
+È uno dei modi più veloci per comunicare, ma è pericoloso:
+può essere necessario controllare i permessi di scrittura.
+Un alternativa sono i __memory mapped files__:
+- primitive semplici (stesse dei file)
+- prestazioni leggermente peggiori
+
+Conviene utilizzare i memory mapped files quando una normale scrittura su filesystem 
+non sarebbe abbastanza veloce.
+
+L'utilizzo della shared memory consiste in:
+- il primo processo crea un segmento di memoria e lo inizializza
+- Altri processi possono accedere al segmento condiviso
+
+La primitiva usata per la creazione è `shmget()` e necessita delle librerie 'ipc.h' e 'shm.h'
+Per poter accedere allo stesso segmento condiviso, i vari processi possono usare la
+chiave che viene restituita al momento della creazione.
+Il segmento più piccolo che può essere allocato è 1 pagina, che può valere 1K,4K,...
+a seconda del sistema.
+Il terzo parametro è un valore bitwise o flag che serve a dare opzioni o 
+impostazioni di sicurezza, le flag vanno usate in OR per ottenere la sequenza i 
+bit di opzioni finali.
+La sincronizzazione migliore viene effettuata con i semafori piuttosto che con 
+i permessi, i permessi servono per questioni di sicurezza.
+
+Con la primitiva `shmat()` che sta per shared memory attach posso collegare il segmento condiviso
+ad altri processi.
+`smhdt()` è un modo per staccare il segmento dal processo chiamante.
+
+### Ciclo di utilizzo di una shared memory
+Operazioni necessarie:
+- Creazione del segmento condiviso
+- Attaccare il segmento a tutti i processi che lo devono usare
+- Staccare il segmento dai processi che hanno finito di usarlo
+- Deallorare il segmento una volta che non serve più
+
+## Memory mapped files
+Diversi processi sono in grado di comunicare con un file condiviso
+In linux a basso livelli il file viene diviso in pezzi della dimensione delle pagine
+per avere un acesso ottimizzato.
+La primitiva usata per questo meccanismo è `mmap()` e dopo la chiamata
+posso accedere all'oggetto con le primitive dei file
+Il file dovrebbe sopravvivere al riavvio del computer.
+La chiamata ad `mmap()` è più flessibile rispetto alle shm ma ha più overhead
+è possibile caricare in memoria con `mmap()` anche file letti dal filesystem (con le primitive dei file)
+
+## Condivisione di dati attraverso una rete IP
+__Remote Procedure Call__ è una procedura remota bloccante eseguita nello spazio 
+di memoria della propria macchina
+Ci sono dei problemi nello scambio di dati, ad esempio può cambiare la endianness tra le due macchine
+e quindi risulterebbe complicato passare dei puntatori.
+RPC è stata la soluzione storica (vecchia di 30anni) per le architetture client server
+rpc si basa su UDP e quindi non garantisce la consegna, in base al valore di ritorno possiamo
+solo dire che la procedura è stata eseguita almeno una volta,
+risulta quindi una buona idea fare funzioni *idempotenti*, cioè che produce lo stesso
+risultato se eseguita più volte.
+__Remote Procedure Call Messages__ di solito usando __External Data Representation__ che è una
+codifica indipendente rispetto alle due macchine e che permette di trasferire i dati
+usando una codifica universale.
+
+### Meccanismo dell' RPC
+- Programma remoto si registra
+- Chiamante ottiene il numero di porta
+- Chiamante codifica i parametri e li invia al remoto
+- Remoto effettua i calcoli, codifica il risultato e lo invia al chiamante.
+
+rpcgen è il compilatore che genera gli stub per server e client.
+
+## Architetture parallele
+- __Shared memory__ in cui più processori usano una memoria condivisa
+Caratterizzati da UniformMemoryAccess (UMA), è l'architettura più semplice
+- __Message passing__ in cui ogni cpu ha una memoria privata consistente
+rispetto alla memoria condivisa, architettura NotUniformMemoryAccess (NUMA)
+- __Distributed systems__ in cui i processori comunicano attraverso internet.
+
+### Aspetti HW dei sistemi multiprocessore
+- Sistemi __UMA__
+Possono usare una matrice crossbar oppure una gerarchia di memorie (come le cache)
+Le architetture UMA funzionano bene per un basso numero di core (<16)
+La memoria condivisa può essere acceduta tramite un bus, con eventuali cache,
+i processori posso utilizzare anche una memoria privata per i conti e scrivere
+il risultato su una memoria condivisa.
+
+Le __matrici crossbar__ hanno il problema che il numero di punti cresce esponenzialmente
+quindi spesso vengono sostituite da switch a strati.
+
+
+

+ 61 - 0
Piattaforme Software per la Rete/MOD2/lesson_08.md

@@ -0,0 +1,61 @@
+# Piattaforme e Software per la rete - lezione 8
+#### William Fornaciari
+###### 14 April 2016
+## Run Time Resource Management
+Necessario per gestire come le applicazioni occupano le risorse
+di elaborazione, posso avere distinzioni tra le applicazioni,
+ad esempio alcune possono essere critiche e non interrompibili
+mentre altre possono essere ritardate se necessario.
+
+Gli obiettivi per RTRM sono:
+- __scalabilità__: il sistema deve funzionare con pochi o molti core
+- __retargetabilità__: il sistema può funzionare su architetture eterogenee.
+L'obiettivo è una __system-wide optimization__ che non si limita solo a
+ricercare delle prestazioni elevate.
+
+Un approccio per dominare e ridurre la complessità del problema 
+è agire in modo *gerarchico*, ad esempio posso avere politiche a livello
+di nodi, o di board...
+
+Quando si lavora su processori sotto i 22nm, trovo il problema della
+__process variability__ cioè un esemplare di un chip funziona
+diversamente da un altro (es: frequenza massima di funzionamento)
+o varia anche da un core all'altro.
+Per questo al momento del mapping tra cpu virtuali e cpu fisiche
+bisogna far attenzione ad alcuni dettagli (non sempre calcolabili)
+Ad esempio se il processo precedente ha scaldato la cpu, il processo
+attuale non potrà sfruttare a pieno il carico termico (problema hot-spot)
+
+Quindi serve fare __accounting__ delle risorse e __monitoring__
+
+### Working Modes
+È l'unione tra la configurazione della piattaforma di calcolo
+e la configurazione dell'applicazione, es:20fps su un quad-core a 800mHz
+Devono esserci dei punti di controllo in modo da cambiare alcuni parametri.
+E devono esserci dei punti di osservabilità per valutare i risultati.
+
+## Barbecue RTRM
+
+*Barbecue* è l'RTRM più avanzato presente sul mercato
+Barbecue effettua il mapping tra le risorse virtuali richieste dalle applicazioni
+sulle risorse fisiche attualmente disponibili.
+
+Nell'aspetto fisico della cpu, data una certa frequenza, ho una tensione minima
+per mantenerlo a quella frequenza, mentre ad una certa tensione la cpu può raggiungere
+una determinata frequenza dipendente da quest'ultima, si cerca quindi di sfruttare
+il punto più vantaggioso tra frequenza e tensione.
+
+Ho molti cicli di controllo, suddivisi su diversi livelli:
+- livello applicazione: ottimizzo utilizzo risorse
+- livello sistema: partiziono le risorse
+- livello firmware
+Quindi a grandi linee ho un sistema __gerarchico distribuito__.
+Barbecue lavora a livello __system-wide__
+
+Durante lo sviluppo di barbecue, è stato risolto il problema multiobiettivo
+del modello teorico di allocazione (simile a knapsack o tsp) ed è stata creata
+un'euristica per ottenere risultati simili al modello teorico.
+L'overhead del sistema è stato limitato al 10%
+
+
+

+ 75 - 0
Piattaforme Software per la Rete/MOD2/lesson_09.md

@@ -0,0 +1,75 @@
+# Piattaforme e Software per la rete - lezione 9
+#### William Fornaciari
+###### 12 May 2016
+## Distributed Process Allocation
+### Migrazione
+Le politiche di scheduling __non migratorie__ Fanno sí che un processo rimanga sulla
+macchina su cui é partito finché non termina
+Le politiche di scheduling __migratorie__ permettono di spostare
+un task giá in esecuzione su una macchina adatta.
+Tuttavia questo introduce dell'*overhead* consistente in:
+- Tempo
+- Consumo energia
+- Quantitá di memoria
+Il problema principale é dovuto allo spostamento dei dati necessari all'applicazione.
+Per quanto riguarda l'energia, non é detto che usare una macchina piú potente migliori
+il rendimento energetico, e inoltre viene spesa energia anche per il trasferimento.
+
+Quindi le migrazioni hanno senso se durano abbastanza a lungo da dare benefici 
+di 10 volte l'overhead, inoltre non é detto che sia possibile interrompere
+l'applicazione per trasferirla.
+
+### Overall design issues
+Potrebbe essere una buona idea allocare i processi su alcune delle cpu e spegnere le altre:
+- Una CPU scarica consuma sempre di piú di una CPU spenta.
+O potrebbe servire tenere delle CPU scariche se si pensa che debba arrivare un picco di utilizzo.
+
+Per quanto riguarda la __logica delle comunicazioni__ Puó essere utile mettere in un sistema distribuito
+due processi che comunicano di frequente sulla stessa macchina, o nel caso siano thread, eventualmente
+incorporarli in un unico processo.
+Se abbiamo grosse moli di dati conviene se possibile metterle sulla stessa macchina che li deve elaborare
+
+Per la __availability__ cioé nel caso di upgrade di componenti hardware puó essere spostata la macchina
+virtuale o nel caso non sia disponibile, solo il processo.
+
+Per quanto riguarda il carico termico, conviene bilanciare il profilo termico spostando il processo
+su varie macchine in modo da mitigare il problema del __thermal breakdown__
+
+### Allocation algorithms: taxonomy
+Gli algoritmi possono essere:
+- Deterministici o euristici
+- Centralizzati o distribuiti
+- Ottimi o sub-ottimi
+
+Un altro aspetto di questi algoritmi é che modificando lo stato del sistema non appena
+si avvicina una situazione sub-ottima, questo puó portare a delle instabilitá.
+
+### Migrazione dei processi
+La migrazione consiste nel trasferire parte dello stato di un processo su una macchina
+di destinazione per permettere il proseguimento.
+La migrazione puó essere avviata dal sistema operativo che possiede il quadro complessivo,
+o dal processo stesso.
+
+### Modellazione con grafi
+Consiste nel tracciare i processi e le dipendenze con nodi e archi, e fare un taglio in modo 
+che la macchina soddisfi i requisiti dei nodi nel taglio, e che i collegamenti esterni siano minimizzati.
+
+### Algoritmo centralizzati
+- Up-Down (manager-worker)
+- Algoritmo euristico (probing)
+- Bidding 
+
+### Negoziazione
+La migrazione dei processi puó avvenire tramite una negoziazione in cui gli starter utility
+dei vari sistemi comunicano prima dello scambio di un processo.
+
+### Eviction
+Puó capitare che una workstation vada in crisi e rimandi al mittente i processi che non siano i propri.
+
+### Co-scheduling
+Spesso conviene migrare i processi in gruppo, 
+ad esempio gruppi di processi che comunicano tra di loro possono essere schedulati per lo stesso time slot
+su macchine diverse, in modo che possano comunicare senza ritardi.
+
+
+

+ 79 - 0
Piattaforme Software per la Rete/MOD2/lesson_10.md

@@ -0,0 +1,79 @@
+# Piattaforme e Software per la rete - lezione 10
+#### William Fornaciari
+###### 13 May 2016
+## Sistemi Multiprocessore
+Tipologie di architetture:
+- Ogni CPU ha il suo SO
+- Sistemi Master-Slave
+- Sistemi Multiprocessore Simmetrici (SMP)
+
+Nel caso di un SO per CPU l'accesso alle periferiche viene gestito tramite
+l'uso di diversi buffer.
+
+Nel caso di sistemi Master Slave, il SO viene eseguito solo dalla CPU __Master__
+Che quindi ha una sola copia dei buffer per I/O
+
+É difficile gestire bene cluster di piú di 8/16 core, a parte nei casi di
+applicazioni nativamente parallelizzate.
+Una tecnica usata é quella del __clustering__ che consiste nel raggruppare CPU
+e usarle in gruppo.
+
+Nelle implementazioni SMP il sistema operativo é singolo ma puó essere eseguito
+da piú processori, tramite l'uso di *lock*
+
+Il __timesharing__ consiste nel dividere il tempo per i processi, 
+ma porta ad un cattivo sfruttamento delle cache, che avrei invece rimettendo lo stesso
+processo sulla stessa CPU.
+
+Lo __space sharing__ in cui k processi vengono assegnati a k CPU disponibili.
+
+Sistemi __Multicomputer__ consistono in uno o piú processori collegati da un interfaccia
+di rete, sono anche usati nelle __network on chip__
+Le topologie di rete usate sono:
+- Stella
+- Anello
+- Mesh
+Le strategie di switching sono:
+- Commutazione di pacchetto
+- Commutazione di circuito
+...
+
+Le risorse di rete possono determinare pesantemente le prestazioni del sistema operativo
+e delle applicazioni eseguite.
+
+Le comunicazioni a livello utente vengono effettuate tramite la chiamata a opportune 
+primitive di sistema
+
+## Sistemi Operativi Real Time (RTOS)
+Sono caratterizzati da un certo __determinismo__ nell'esecuzione, e da una importanza
+nei tempi di risposta.
+Spesso le applicazioni eseguite da sistemi RTOS hanno dei *Time Constraints*
+che consistono nei momenti in cui i processi vengono richiesti e nelle *deadline*
+per la terminazione di questi ultimi, che possono essere soft o hard a seconda 
+dell'importanza
+Inoltre puó esserci o meno la __preemption__ dei processi che determina se essi
+vengono sostituiti in presenza di interrupt.
+
+### Scheduling
+Per lo scheduling a grana sottile vengono usati algoritmi semplici e veloci come 
+*round robin*, mentre per lo scheduling a grana grossa vengono usati algoritmi
+piú sofisticati.
+
+Esistono diversi algoritmi di scheduling, con o senza preemption e offrono
+tempi di risposta diversi
+Esempi:
+- Fixed priority scheduling
+
+__Fattori che possono influenzare lo scheduling__
+- Analisi di schedulabilitá:
+   - Fatta o non fatta
+   - Online o offline
+- Prioritá
+
+Di particolare nota é lo scheduler __Rate Monotonic__ che é in grado di garantire
+in modo dimostrabile il rispetto delle deadlines e un buon utilizzo generale della CPU.
+
+Guardo slides su RTX
+
+
+

+ 10 - 0
Principles of Programming Languages/lesson_01.md

@@ -0,0 +1,10 @@
+# PLP - lesson 01
+##### Matteo Pradella
+## Introduction
+
+__web-page__:
+
+20 years ago compilers were usually bought.
+Thanks to the open source movement, now we have free compilers and environments for almost all programming languages.
+
+[www.scheme.com/tsp14]  

+ 135 - 0
Segnali/lesson_01.md

@@ -0,0 +1,135 @@
+# Segnali e Sistemi per le Telecomunicazioni
+#### Claudio Prati
+###### 6 March 2017
+#### Prima lezione
+
+## Introduzione
+Le lezioni seguono il libro di testo.
+
+Nel corso verranno spiegate delle tecniche per codificare e trasmettere
+informazioni nel campo delle telecomunicazioni.
+
+Studieremo delle tecniche deterministiche e razionali, ma non sono le uniche
+possibili, infatti esistono i meccanismi di reti neurali e machine learning che
+sono in grado di apprendere meccanismi complicati in modo semplice.
+
+Alcuni dei problemi si possono risolvere con tecniche classiche/razionali, usare
+gli algoritmi machine learning per risolvere questi problemi é overkill.
+
+Alcuni segnali possono essere modellizzati come funzione di una variabile.
+Mentre altri segnali non possono essere rappresentati come funzioni ma sono
+comunque offetto di studi, ad esempio una registrazione della voce.
+
+Altre tecniche interessanti sono quelle che permettono di ridurre il rumore di
+un segnale, ad esempio usate per pulire il segnale ricevuto dalle sonde nello
+spazio.
+
+### Dettagli sul corso
+Lunedí inizia alle 16:15
+Mercoledí si fanno 3 ore normalmente, iniziando alle 14:30,
+la quarta ora si fará in via eccezionale se servisse recuperare delle lezioni.
+Il venerdí si comincia alle 8:15
+
+Il __laboratorio__ consiste nell'applicare in matlab le cose spiegate in teoria,
+non é oggetto dell'esame ma interessante e utile per capire meglio i concetti.
+
+Il __libro di testo__ é scritto da Prati.
+
+__Esami__: no prove intermedie, 2 appelli per sessione con possibilitá di
+anticipare uno dei due appelli prima dell'inizio della sessione.
+Quindi é possibile fare due appelli su tre date.
+All'esame é possibile portare tutto il materiale che si vuole.
+
+Il __materiale didattico__ si puó trovare dalla pagina del personale DEIB di
+Prati, nella sessione *materiale didattico*, in cui sono presenti tutti i temi
+d´ esame dal 2007, i file di matlab e il formulario.
+
+__contatti:__ l'orario di ricevimento é il martedí... ma non viene seguito dal
+docente, peró se si manda un email al professore ci si puó mettere d'accordo.
+email:*claudio.prati@polimi.it*
+
+### Preconcetti
+Una __funzione__ é un valore intero, reale o complesso che varia in base ad un
+altro valore, detto variabile indipendente puó essere rappresentato in una 
+tabella o in un grafico.
+
+La variabile indipendente é spesso il tempo ma non é per forza cosí.
+Infatti esistono sistemi anticausali in cui l'uscita avviene prima
+dell'ingresso, e questi sistemi non possono essere spiegati usando il tempo come
+variabile.
+L'unico film che risolve il paradosso del tempo é Interstellar, e lo fa usando
+il concetto di universi paralleli, altre soluzioni ricadono in un paradosso
+circolare.
+
+Se consideriamo __lo spazio come variabile__ e non il tempo, abbiamo per un certo
+stimolo, degli effetti causali e degli effetti anticausali.
+
+Una prima funzione é 
+$$X(t) = cos(2\pit)$$
+La rappresentazione grafica é semplice
+
+Se trattiamo una funzione complessa é questa
+$$X(t)= cos(2pit) + jsin(2pit)$$
+Ha una parte reale e una parte immaginaria, qindi per rappresentarla
+graficamente devo usare due grafici, uno per la parte reale e uno per la parte
+immaginaria.
+Una seconda rappresentazione é quella polare in cui i due grafici sono modulo e
+angolo, l'angolo in teoria dei segnali viene chiamato *fase*.
+
+
+Il modulo del grafico polare é $|x(t)| = sqrt(cos^2(2pit)+sin^2(2pit))=1)$
+Mentre la fase é $fase x(t) = \arctg(\sin(2\pit)/\cos(2\pit))=2\pit$
+
+Matlab potrebbe dare una rappresentazione diversa del grafico della fase, a
+dente di sega, e questo é grazie al fatto che gli angoli si ripetono ogni $2\pi$
+
+L'ambiguitá di $2\pi$ permetterá di risolvere in modo esatto il problema del
+campionamento.
+
+Se prendiamo un __segnale discreto__, possiamo rappresentare un segnale
+continuo in in forma discreta, come una sequenza di numeri 
+$$X(nT)=\cos(2\pinT)$$.
+
+Il calcolatore per T=1/4 legge una formula $cos(2\pin/4)=X_n$
+La formula numerica dei campioni viene rappresentata col simbolo $X_n$ a
+differenza di quella grafica che viene rappresentata con $nT$
+
+L'elenco di segnali che affronteremo nel corso é:
+- Segnali continui reali e complessi
+- Segnali discreti
+
+Entrambe le tipologie di segnali possono essere:
+- periodici
+- aperiodici
+
+### Operazioni elementari sui segnali
+__Traslazione__:
+$$X(t-\tau)$$
+Il segnale originale $X(t)$ viene spostato verso sinistra (viene ritardato), in
+pratica stiamo modificando l'asse dei tempi, non il segnale.
+$X(t-\tau)$ ad esempio é un anticipo
+
+__Scalatura__:
+$$X(at)$$
+Se $a>1$ il tempo diventa piú veloce e il segnale *dimagrisce*
+Se $a<1$ ho dilatato il tempo e il segnale risulta *ingrassato*
+
+__Scalatura e traslazione__:
+$$X(at-\tau)$$
+Le due operazioni vanno effettuate in un ordine preciso, in base alla forma in
+cui é espresso il segnale, ad esempio:
+- __Prima la traslazione__
+- __Poi la scalatura__
+$$X(\xi)$$
+$$\xi = at - \tau$$
+$$t = (\xi+\tau)\a$$
+
+$$\Tilde{X}(t)=\Sum_{-\inf}^{+\inf}(X(t-nT_0))$$
+$$\Tilde{X}_n=\Sum_{-\inf}^{+\inf}i(X_{n-kN_o}))$$
+
+Energia di un segnale qualsiasi
+$$E_{x(t)}=\Int_{-\inf}^{+\inf}|X(t)|^2dt$$
+
+Potenza di un segnale periodico
+$$P_{x(t)}=\Lim_{T->\Inf} 1/T
+\Int_{-T/2}^{T/2}|X(t)^2dt=1/T_0\Int_{T_0}|X(t)|^2dL$$

+ 5 - 0
lesson_temp.md

@@ -0,0 +1,5 @@
+# Piattaforme e Software per la rete - lezione 2
+#### William Fornaciari
+###### 10 March 2016
+## Modulo 2
+

+ 7 - 0
makefile

@@ -0,0 +1,7 @@
+all: concatenate
+
+[lesson_]%.pdf:	[lesson_]%.md 
+	pandoc --latex-engine=xelatex -t latex+tex_math_dollars -o $@ $<
+
+concatenate: [lesson_]%.pdf
+	pdftk $< cat output complete.pdf

+ 2 - 0
markdown2pdf.sh

@@ -0,0 +1,2 @@
+for file in *.md; do pandoc --latex-engine=xelatex -t latex+tex_math_dollars -o 
+$file.pdf $file; done

+ 3 - 0
markdown2pdf2.sh

@@ -0,0 +1,3 @@
+for i in {1..10}; do pandoc --latex-engine=xelatex -t 
+latex+tex_math_dollars -o lesson_$i.pdf lesson_$i.md; done
+

+ 34 - 0
polimd_archived/operations_research/lesson_01.md

@@ -0,0 +1,34 @@
+# Operations Research
+#### Enrico Malucelli
+##### 6 October 2015
+## Introduction
+### What is Operations Research?
+Is a method of taking decisions using math
+
+Typically we solve optimization problems daily withoud being conscious
+
+        Confucius
+
+        I hear and forget,
+        I see and remember,
+        I do and understand.
+####Interesting sites:
+
+
+### What kind of decisions?
+- __Strategic__ Level: design a railroad
+- __Tactical__ level: how many trains to use
+- __Operational__ level: schedule the trains
+
+### How OR approaches the problems
+- __Decisions__
+- __Rules__ Mathematical constraints
+- __Objective__ Maximize the income
+#### Solution to phone building example:
+- plot the constraints in a 2D graph
+- select the region below all the constraints
+- Find the optimal solution analyzing the vertexes of the polygon.
+
+(In this case the vertex were integers but they may be real numbers and the solution is required to be integer.)
+### Challenges
+http://challenge.roadef.org/2016/en/index.php

+ 97 - 0
polimd_archived/operations_research/lesson_02.md

@@ -0,0 +1,97 @@
+# Operations Research
+#### Enrico Malucelli
+##### 6 October 2015
+## Introduction
+### Exercise: How to invest a budget
+
+###Steps
+#### 1. decisions
+#### 2. constraints
+
+####Solution
+#####Variables
+$x_i$= amount of money invested
+(i=1...5), $x_i \ge 0$
+#####constraints
+$\sum x_i \le 137$
+
+$x_1 \le 40$
+
+$x_2 \le 12$
+
+$x_3 \le 130$
+
+$x_4 \le 5$
+
+$x_5 \le 400$
+#####target
+$x_1/40*3.2+x_2/12*1.5+x_3/130*4.2+x_4/5*0.7+x_5/400*17$
+
+####Alternative solution
+$y_1$=share of bond
+$y_1=x_1/availability$
+$0 \le y_1\le1$
+$i=1$
+
+$$40y_1+12y_2+130y_3+5y_4+400y_5\le137$$
+$$max32y_1+15y_2+4.2y_3+0.7y_4+17y_5$$
+
+We can divide each bonus for the total of the earning so we can get an index of the best investment.
+$$8\%y_1+125\%y_2+3.2\%y_3+14\%y_4+4.25\%y_5$$
+
+We notice that the $y_2$ is the best investment, and we should buy as much as we can of that kind.
+
+example:
+$y_4=1$
+$y_2=1$
+$y_1=1$
+$y_5=...$
+####Algorithm generalization
+$$\sum c_i y_i$$
+$$\sum a_i y_i \le b$$
+$$0\le y_i \le 1 i=1 \mu$$
+Sort indicates by non decreasing $C_i/a_i$ cosider the variables in the Order:
+$$y_i=\begin{cases} 1,& if &b \ge a_i\\
+b/a_i,& if &b < a_i
+\end{cases}$$
+$$b-y_ia_i$$
+
+###Logical variables
+Can assume only the values $\{0,1\}$
+####example:
+A burglar sneaks into a jewelry and his bag can hold 8kg, what must he steal?
+
+|| object | 1 | 2 | 3 | 4 | 5 | 6 |
+|-------|--------|---|---|---|---|---|---|
+| value | $v_i$  | 7 | 2 | 4 | 5 | 4 | 1 |
+|weight|$w_i$|5|3|2|3|1|1|
+####solution
+Contrary to the previous problem (in which we had infinite solutions, like any fraction), in this problem we have at most $2^6$ solutions, maybe not all of them are feasible.
+
+x_i = 1 if the burglar has taken, 0 otherwise
+
+$$max \sum v_i x_i$$
+$$\sum w_i x_i \le b(=8)$$
+
+If we apply the same algorithm as before, we can calculate the value_for_weight factor of every object and choose the best ones.
+#####However this is not the best solution
+####Logical variable, __Complement__
+$$x'_i=1-x_i$$
+####Other types of variables
+####Integer Variables
+####Discrete value variables
+In most cases we select the value of a variable within a __finite set__
+e.g.: the memory size of a computer, the capacity of a telecommunication link.
+$$x\in \{ v_1,v_2,...,v_r\}$$
+#####formulas
+$$s_i=\begin{cases}
+1,& x=v_i\\
+0,& \end{cases}$$
+###example: diet
+|food|pasta|rice|steak|carrots|potatoes|pear|
+|----|-----|----|-----|-------|--------|----|
+|calories per hg|300|250|200|70|180|100
+####Minimum required calories: __700__
+We can transform all the inequalities to be less or equal
+
+And later we need to transform our inequalities into equalities

+ 0 - 0
polimd_archived/operations_research/note_follows_on_paper


+ 95 - 0
polimd_archived/soft_computing/lesson_01.md

@@ -0,0 +1,95 @@
+# Soft Computing
+#### Andrea Bonarini
+##### 5 October 2015
+
+#### What is Soft Computing?
+
+The term was introduced by Lotfi Zadeh, the father of fuzzy sets,
+to denote programming techniques not related to *traditional* programming languages:
+- Fuzzy systems
+- Neural networks
+- Stochastic systems
+
+##### definition
+A set of techniques to model systems (input-output mapping) by approximating them.
+
+##### Modelling technique: generalization
+Considers a small sample of the entity to make an approximate model,
+
+
+#### Model
+
+- Is a *representation* of some entity, defined for a *specific purpose*.
+
+- Is limited to aspects of the entity represented which are *relevant for the purpose*
+
+- A model is different to the represented entity ex: map vs land
+
+- Models lead to *approximation, uncertainty, imprecision*.
+
+##### Approximation
+The model features are similar to the real ones but not the same.
+##### Uncertainty
+We are not sure that the features of the model are the same of the entity.
+##### Imprecision
+The model features values are not precise.
+
+#### Techniques
+
+- ##### Fuzzy sets:
+    Correct model in a finite number of points, smooth transistion (approximation) among them.
+
+    ex: in a thermal control system we fix the normal working point and the critical one, and the system approximates the behaviour between.
+
+- ##### Neural networks
+    input-output samples, learning algorithms to define output values for unknown values.
+
+- ##### Genetic algorithms
+    Optimal solution, obtained by evaluating populations of tentative solutions and combining their parts (sort of copying from nature).
+
+#### Applications:
+
+From washing machines to helicopters, to rice cookers
+
+### Fuzzy Sets
+
+Were created in 1965 by Lotfi Zadeh
+
+The principle is to make computation with words.
+
+#### What is a fuzzy set?
+Is a set whose membership function can range on the interval [0,1].
+
+On contrary to __crisp sets__ that admit only {0,1}
+
+###### A membership function defines a set
+###### Defines the degree of membership of an element to the set
+μ: U -> [0,1]
+
+#### How to define membership functions
+- select a variable
+    - distance
+- define a range of the variable
+    - [0..10]
+- identify labels
+    - close, medium, far
+- for each label identify the charachteristic points
+    - 0, max, middle values, where MF=1, ...
+- identify function shapes
+    - linear
+- check
+
+#####Membership functions can also overlap,
+and this quality is useful for example in classification of a noisy input,
+in fact with overlapping MF we have a *smooth transition* from a label to another
+
+#### MF and concepts
+
+__MFs__ define __fuzzy sets__
+
+__Labels__ denote __fuzzy sets__
+
+__Fuzzy sets__ can be considered as conceptual representations
+
+#### Symbol grounding
+Reason in terms of concepts and grounds them to reality.

+ 34 - 0
polimd_archived/soft_computing/lesson_02.md

@@ -0,0 +1,34 @@
+# Soft Computing
+#### Andrea Bonarini
+##### 8 October 2015
+
+#### Membership Function and concepts
+
+#### Propertise of a frame of cognition
+each fuzzy set is called a __granule__
+- __Coverage__:each value belong at least to a value
+
+### Robustness
+
+### $\alpha$-cuts
+
+### Support of a fuzzy set
+
+### Height of a fuzzy set
+
+### Strange MF
+
+####Singleton
+A fuzzy set with one member
+
+### Standard operators of fuzzy sets
+
+__Complement__
+
+$\mu_f(x)=1-\mu_f(x)$
+
+__Union__
+
+The maximum of two fuzzy sets
+
+__Intersection__

+ 0 - 0
polimd_archived/soft_computing/note_follows_on_paper