leader.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  1. package main
  2. //#cgo CFLAGS: -fopenmp -O2
  3. //#cgo LDFLAGS: -lcrypto -lm -fopenmp
  4. //#include "../c/dpf.h"
  5. //#include "../c/okv.h"
  6. //#include "../c/dpf.c"
  7. //#include "../c/okv.c"
  8. import "C"
  9. import (
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/sha256"
  13. "crypto/tls"
  14. "crypto/x509"
  15. "crypto/x509/pkix"
  16. "encoding/pem"
  17. "fmt"
  18. "log"
  19. "math"
  20. "math/big"
  21. mr "math/rand"
  22. "net"
  23. "os"
  24. "sort"
  25. "strings"
  26. "sync"
  27. "time"
  28. lib "2PPS/lib"
  29. "unsafe"
  30. "golang.org/x/crypto/nacl/box"
  31. )
  32. //this stores all neccessary information for each client
  33. type clientKeys struct {
  34. roundsParticipating int
  35. PublicKey *[32]byte
  36. SharedSecret [32]byte
  37. PirQuery [][]byte
  38. }
  39. var clientData = make(map[net.Addr]clientKeys)
  40. const follower string = "127.0.0.1:4442"
  41. //Maximum Transport Unit
  42. const mtu int = 1100
  43. var leaderPrivateKey *[32]byte
  44. var leaderPublicKey *[32]byte
  45. var followerPublicKey *[32]byte
  46. const maxNumberOfClients = 1000000
  47. var topicList []byte
  48. var topicAmount int
  49. var archiveTopicAmount int
  50. // every roundsBeforeUpdate the client updates his pirQuery
  51. const roundsBeforeUpdate = 2
  52. const neededSubscriptions = 5
  53. const numThreads = 12
  54. const dataLength = 256
  55. const minDBWriteSize = 1000
  56. var dbWriteSize float64 = 10000
  57. //this is the number of positions for auditing
  58. var extraPositions int = 2
  59. var collisionCounter []float64
  60. var clientsConnected float64
  61. var maxTimePerRound time.Duration = 10 * time.Second
  62. var clientsServedPhase1 []int
  63. var clientsServedPhase3 []int
  64. var startPhase1 time.Time
  65. var startPhase2 time.Time
  66. var startPhase3 time.Time
  67. //counts the number of rounds
  68. var round int
  69. var startTime time.Time
  70. var startTimeRound time.Time
  71. //channel for goroutine communication with clients
  72. var phase1Channel = make(chan net.Conn, maxNumberOfClients)
  73. var phase3Channel = make(chan net.Conn, maxNumberOfClients)
  74. //variables for calculating the dbWrite size
  75. const publisherRounds int = 10
  76. var publisherAmount float64
  77. var publisherHistory [publisherRounds]int
  78. //only prints auditing time for one client per round
  79. var firstAuditPrint bool
  80. var auditingStart time.Time
  81. var auditingEnd time.Time
  82. var firstTweetSend bool
  83. func main() {
  84. f, err := os.OpenFile("evalData", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  85. if err != nil {
  86. log.Fatalf("error opening file: %v", err)
  87. }
  88. defer f.Close()
  89. log.SetOutput(f)
  90. log.Println("roundsBeforeUpdate", roundsBeforeUpdate)
  91. log.Println("neededSubscriptions", neededSubscriptions)
  92. log.Println("dataLength", dataLength)
  93. log.Println("maxTimePerRound~", maxTimePerRound*3)
  94. log.Println("extraPositions", extraPositions)
  95. log.Println("numClients", 500)
  96. log.Println("Archiving is done every 24h, no Clients wants Archive")
  97. //prevents race conditions for wrtiting
  98. m := &sync.RWMutex{}
  99. startTime = time.Now()
  100. clientsServedPhase1 = make([]int, 1000)
  101. clientsServedPhase3 = make([]int, 1000)
  102. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  103. if err != nil {
  104. panic(err)
  105. }
  106. //why is this neccessary?
  107. leaderPrivateKey = generatedPrivateKey
  108. leaderPublicKey = generatedPublicKey
  109. C.initializeServer(C.int(numThreads))
  110. //calls follower for setup
  111. conf := &tls.Config{
  112. InsecureSkipVerify: true,
  113. }
  114. followerConnection, err := tls.Dial("tcp", follower, conf)
  115. if err != nil {
  116. panic(err)
  117. }
  118. followerConnection.SetDeadline(time.Time{})
  119. //receives follower publicKey
  120. var tmpFollowerPubKey [32]byte
  121. _, err = followerConnection.Read(tmpFollowerPubKey[:])
  122. if err != nil {
  123. panic(err)
  124. }
  125. followerPublicKey = &tmpFollowerPubKey
  126. //send publicKey to follower
  127. writeTo(followerConnection, leaderPublicKey[:])
  128. writeTo(followerConnection, intToByte(neededSubscriptions))
  129. //goroutine for accepting new clients
  130. go func() {
  131. leaderConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  132. if err != nil {
  133. panic(err)
  134. }
  135. // Generate a pem block with the private key
  136. keyPem := pem.EncodeToMemory(&pem.Block{
  137. Type: "RSA PRIVATE KEY",
  138. Bytes: x509.MarshalPKCS1PrivateKey(leaderConnectionPrivateKey),
  139. })
  140. tml := x509.Certificate{
  141. // you can add any attr that you need
  142. NotBefore: time.Now(),
  143. NotAfter: time.Now().AddDate(5, 0, 0),
  144. // you have to generate a different serial number each execution
  145. SerialNumber: big.NewInt(123123),
  146. Subject: pkix.Name{
  147. CommonName: "New Name",
  148. Organization: []string{"New Org."},
  149. },
  150. BasicConstraintsValid: true,
  151. }
  152. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &leaderConnectionPrivateKey.PublicKey, leaderConnectionPrivateKey)
  153. if err != nil {
  154. panic(err)
  155. }
  156. // Generate a pem block with the certificate
  157. certPem := pem.EncodeToMemory(&pem.Block{
  158. Type: "CERTIFICATE",
  159. Bytes: cert,
  160. })
  161. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  162. if err != nil {
  163. panic(err)
  164. }
  165. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  166. //listens for clients
  167. lnClients, err := tls.Listen("tcp", ":4441", config)
  168. if err != nil {
  169. panic(err)
  170. }
  171. defer lnClients.Close()
  172. for {
  173. clientConnection, err := lnClients.Accept()
  174. if err != nil {
  175. fmt.Println("Client connection error 1", err)
  176. clientConnection.Close()
  177. break
  178. }
  179. clientConnection.SetDeadline(time.Time{})
  180. //sends topicList so client can participate in phase 3 asap
  181. errorBool := sendTopicLists(clientConnection, followerConnection, true)
  182. if errorBool {
  183. break
  184. }
  185. //send leader publicKey
  186. _, err = clientConnection.Write(leaderPublicKey[:])
  187. if err != nil {
  188. fmt.Println("Client connection error 2", err)
  189. clientConnection.Close()
  190. break
  191. }
  192. //send follower publicKey
  193. _, err = clientConnection.Write(followerPublicKey[:])
  194. if err != nil {
  195. fmt.Println("Client connection error 3", err)
  196. clientConnection.Close()
  197. break
  198. }
  199. var clientPublicKey *[32]byte
  200. var tmpClientPublicKey [32]byte
  201. //gets publicKey from client
  202. _, err = clientConnection.Read(tmpClientPublicKey[:])
  203. if err != nil {
  204. fmt.Println("Client connection error 4", err)
  205. clientConnection.Close()
  206. break
  207. }
  208. _, err = clientConnection.Write(intToByte(neededSubscriptions))
  209. if err != nil {
  210. fmt.Println("Client connection error 5", err)
  211. clientConnection.Close()
  212. break
  213. }
  214. _, err = clientConnection.Write(intToByte(int(startTime.Unix())))
  215. if err != nil {
  216. fmt.Println("Client connection error 6", err)
  217. clientConnection.Close()
  218. break
  219. }
  220. clientPublicKey = &tmpClientPublicKey
  221. //this is the key for map(client data)
  222. remoteAddress := clientConnection.RemoteAddr()
  223. //pirQuery will be added in phase 3
  224. //bs! only want to set roundsParticipating and answerAmount to 0, mb there is a better way
  225. //will work for now
  226. var emptyArray [32]byte
  227. var emptyByteArray [][]byte
  228. keys := clientKeys{0, clientPublicKey, emptyArray, emptyByteArray}
  229. m.Lock()
  230. clientData[remoteAddress] = keys
  231. m.Unlock()
  232. phase1Channel <- clientConnection
  233. clientsConnected++
  234. }
  235. }()
  236. wg := &sync.WaitGroup{}
  237. //the current phase
  238. phase := make([]byte, 1)
  239. for {
  240. startPhase1 = time.Now()
  241. startTimeRound = time.Now()
  242. phase[0] = 1
  243. round++
  244. fmt.Println("clientsServedPhase1", clientsServedPhase1[round-1])
  245. fmt.Println("clientsServedPhase3", clientsServedPhase3[round-1])
  246. fmt.Println("dbWriteSize", dbWriteSize)
  247. log.Println()
  248. log.Println("Phase 1 Round", round)
  249. log.Println()
  250. bytesSaved := lib.GetBytesSaved()
  251. //todo! doesnt work
  252. log.Println("bytesSaved Percentage", bytesSaved)
  253. firstAuditPrint = true
  254. //creates a new write Db for this round
  255. for i := 0; i < int(dbWriteSize); i++ {
  256. C.createDb(C.int(1), C.int(dataLength))
  257. }
  258. //creates a new db containing virtual addresses for auditing
  259. virtualAddresses := createVirtualAddresses()
  260. //send all virtualAddresses to follower
  261. for i := 0; i <= int(dbWriteSize); i++ {
  262. writeTo(followerConnection, intToByte(virtualAddresses[i]))
  263. }
  264. //moves all clients to phase1
  265. if len(phase3Channel) > 0 {
  266. for client := range phase3Channel {
  267. phase1Channel <- client
  268. if len(phase3Channel) == 0 {
  269. break
  270. }
  271. }
  272. }
  273. for id := 0; id < numThreads; id++ {
  274. wg.Add(1)
  275. followerConnection, err := tls.Dial("tcp", follower, conf)
  276. if err != nil {
  277. panic(err)
  278. }
  279. followerConnection.SetDeadline(time.Time{})
  280. go phase1(id, phase, followerConnection, wg, m, virtualAddresses)
  281. }
  282. wg.Wait()
  283. //log.Println("fullDurationPhase1", time.Since(startPhase1).Seconds())
  284. log.Println("fullAuditingDuration~", auditingEnd.Sub(auditingStart).Seconds()*clientsConnected)
  285. log.Println("auditingPercentage", (auditingEnd.Sub(auditingStart).Seconds()*clientsConnected)/(time.Since(startPhase1).Seconds()))
  286. //Phase 2
  287. startPhase2 = time.Now()
  288. followerConnection, err := tls.Dial("tcp", follower, conf)
  289. if err != nil {
  290. panic(err)
  291. }
  292. followerConnection.SetDeadline(time.Time{})
  293. phase2(followerConnection)
  294. //log.Println("fullDurationPhase2", time.Since(startPhase2).Seconds())
  295. //Phase 3
  296. //moves all clients to phase3
  297. if len(phase1Channel) > 0 {
  298. for client := range phase1Channel {
  299. phase3Channel <- client
  300. if len(phase1Channel) == 0 {
  301. break
  302. }
  303. }
  304. }
  305. startPhase3 = time.Now()
  306. //no tweets -> continue to phase 1 and mb get tweets
  307. topicList, topicAmount = lib.GetTopicList(0)
  308. if len(topicList) == 0 {
  309. continue
  310. }
  311. firstTweetSend = true
  312. phase[0] = 3
  313. startTimeRound = time.Now()
  314. for id := 0; id < numThreads; id++ {
  315. wg.Add(1)
  316. followerConnection, err := tls.Dial("tcp", follower, conf)
  317. if err != nil {
  318. panic(err)
  319. }
  320. followerConnection.SetDeadline(time.Time{})
  321. go phase3(id, phase, followerConnection, wg, m)
  322. }
  323. wg.Wait()
  324. log.Println("fullDurationPhase3", time.Since(startPhase3).Seconds())
  325. lib.CleanUpdbR(round)
  326. }
  327. }
  328. func phase1(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex, virtualAddresses []int) {
  329. roundAsBytes := intToByte(round)
  330. gotClient := make([]byte, 1)
  331. gotClient[0] = 0
  332. //wait until time is up
  333. for len(phase1Channel) == 0 {
  334. if time.Since(startTimeRound) > maxTimePerRound {
  335. //tells follower that this worker is done
  336. writeTo(followerConnection, gotClient)
  337. wg.Done()
  338. return
  339. }
  340. time.Sleep(1 * time.Second)
  341. }
  342. for clientConnection := range phase1Channel {
  343. clientsServedPhase1[round] = clientsServedPhase1[round] + 1
  344. gotClient[0] = 1
  345. //tells follower that this worker got a clientConnection
  346. writeTo(followerConnection, gotClient)
  347. //sends clients publicKey to follower
  348. m.RLock()
  349. clientPublicKey := clientData[clientConnection.RemoteAddr()].PublicKey
  350. m.RUnlock()
  351. writeTo(followerConnection, clientPublicKey[:])
  352. //setup the worker-specific db
  353. dbSize := int(C.dbSize)
  354. db := make([][]byte, dbSize)
  355. for i := 0; i < dbSize; i++ {
  356. db[i] = make([]byte, int(C.db[i].dataSize))
  357. }
  358. //tells client that phase 1 has begun
  359. errorBool := writeToWError(clientConnection, phase, followerConnection, 5)
  360. if errorBool {
  361. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  362. if contBool {
  363. continue
  364. } else {
  365. return
  366. }
  367. }
  368. //tells client current dbWriteSize
  369. errorBool = writeToWError(clientConnection, intToByte(int(dbWriteSize)), followerConnection, 5)
  370. if errorBool {
  371. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  372. if contBool {
  373. continue
  374. } else {
  375. return
  376. }
  377. }
  378. //tells client current round
  379. errorBool = writeToWError(clientConnection, roundAsBytes, followerConnection, 5)
  380. if errorBool {
  381. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  382. if contBool {
  383. continue
  384. } else {
  385. return
  386. }
  387. }
  388. //begin auditing
  389. if id == 0 && firstAuditPrint {
  390. auditingStart = time.Now()
  391. }
  392. m.RLock()
  393. var clientKeys = clientData[clientConnection.RemoteAddr()]
  394. m.RUnlock()
  395. clientKeys, pirQuery, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, 0, true)
  396. if errorBool {
  397. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  398. if contBool {
  399. continue
  400. } else {
  401. return
  402. }
  403. }
  404. errorBool = getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, clientConnection, followerConnection)
  405. if errorBool {
  406. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  407. if contBool {
  408. continue
  409. } else {
  410. return
  411. }
  412. }
  413. if id == 0 && firstAuditPrint {
  414. firstAuditPrint = false
  415. auditingEnd = time.Now()
  416. log.Println("Auditing duration", time.Since(auditingStart).Seconds(), "numVirtualAddresses", len(virtualAddresses))
  417. }
  418. m.Lock()
  419. clientData[clientConnection.RemoteAddr()] = clientKeys
  420. m.Unlock()
  421. //accept dpfQuery from client
  422. dpfLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  423. if errorBool {
  424. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  425. if contBool {
  426. continue
  427. } else {
  428. return
  429. }
  430. }
  431. dpfLength := byteToInt(dpfLengthBytes)
  432. dpfQueryAEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  433. if errorBool {
  434. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  435. if contBool {
  436. continue
  437. } else {
  438. return
  439. }
  440. }
  441. dpfQueryBEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  442. if errorBool {
  443. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  444. if contBool {
  445. continue
  446. } else {
  447. return
  448. }
  449. }
  450. writeToWError(followerConnection, dpfLengthBytes, nil, 0)
  451. writeToWError(followerConnection, dpfQueryBEncrypted, nil, 0)
  452. //decrypt dpfQueryA for sorting into db
  453. var decryptNonce [24]byte
  454. copy(decryptNonce[:], dpfQueryAEncrypted[:24])
  455. dpfQueryA, ok := box.Open(nil, dpfQueryAEncrypted[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  456. if !ok {
  457. panic("dpfQueryA decryption not ok")
  458. }
  459. ds := int(C.db[0].dataSize)
  460. dataShareLeader := make([]byte, ds)
  461. pos := C.getUint128_t(C.int(virtualAddresses[int(dbWriteSize)]))
  462. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShareLeader[0]))
  463. dataShareFollower, _ := readFrom(followerConnection, ds, nil, 0)
  464. writeToWError(followerConnection, dataShareLeader, nil, 0)
  465. auditXOR := make([]byte, ds)
  466. passedAudit := true
  467. for i := 0; i < ds; i++ {
  468. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  469. //client tried to write to a position that is not a virtuallAddress
  470. if auditXOR[i] != 0 {
  471. clientConnection.Close()
  472. passedAudit = false
  473. }
  474. }
  475. if passedAudit {
  476. //run dpf, xor into local db
  477. for i := 0; i < dbSize; i++ {
  478. ds := int(C.db[i].dataSize)
  479. dataShare := make([]byte, ds)
  480. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  481. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  482. for j := 0; j < ds; j++ {
  483. db[i][j] = db[i][j] ^ dataShare[j]
  484. }
  485. }
  486. //xor the worker's DB into the main DB
  487. for i := 0; i < dbSize; i++ {
  488. m.Lock()
  489. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  490. m.Unlock()
  491. }
  492. phase3Channel <- clientConnection
  493. }
  494. //loop that waits for new client or leaves phase1 if time is up
  495. for {
  496. if time.Since(startTimeRound) < maxTimePerRound {
  497. //this worker handles the next client
  498. if len(phase1Channel) > 0 {
  499. break
  500. //this worker waits for next client
  501. } else {
  502. time.Sleep(1 * time.Second)
  503. }
  504. //times up
  505. } else {
  506. //tells follower that this worker is done
  507. gotClient[0] = 0
  508. writeTo(followerConnection, gotClient)
  509. wg.Done()
  510. return
  511. }
  512. }
  513. }
  514. }
  515. func phase2(followerConnection net.Conn) {
  516. //gets current seed
  517. seedLeader := make([]byte, 16)
  518. C.readSeed((*C.uchar)(&seedLeader[0]))
  519. //get data
  520. dbSize := int(C.dbSize)
  521. tmpdbLeader := make([][]byte, dbSize)
  522. for i := range tmpdbLeader {
  523. tmpdbLeader[i] = make([]byte, dataLength)
  524. }
  525. for i := 0; i < dbSize; i++ {
  526. C.readData(C.int(i), (*C.uchar)(&tmpdbLeader[i][0]))
  527. }
  528. //writes seed to follower
  529. writeTo(followerConnection, seedLeader)
  530. //write data to follower
  531. //this is surely inefficent
  532. for i := 0; i < dbSize; i++ {
  533. writeTo(followerConnection, tmpdbLeader[i])
  534. }
  535. //receive seed from follower
  536. seedFollower, _ := readFrom(followerConnection, 16, nil, 0)
  537. //receive data from follower
  538. tmpdbFollower := make([][]byte, dbSize)
  539. for i := range tmpdbFollower {
  540. tmpdbFollower[i] = make([]byte, dataLength)
  541. }
  542. for i := 0; i < dbSize; i++ {
  543. tmpdbFollower[i], _ = readFrom(followerConnection, dataLength, nil, 0)
  544. }
  545. //put together the db
  546. tmpdb := make([][]byte, dbSize)
  547. for i := range tmpdb {
  548. tmpdb[i] = make([]byte, dataLength)
  549. }
  550. //get own Ciphers
  551. ciphersLeader := make([]*C.uchar, dbSize)
  552. for i := 0; i < dbSize; i++ {
  553. ciphersLeader[i] = (*C.uchar)(C.malloc(16))
  554. }
  555. for i := 0; i < dbSize; i++ {
  556. C.getCipher(1, C.int(i), ciphersLeader[i])
  557. }
  558. //send own Ciphers to follower
  559. for i := 0; i < dbSize; i++ {
  560. writeTo(followerConnection, C.GoBytes(unsafe.Pointer(ciphersLeader[i]), 16))
  561. }
  562. //receive ciphers from follower
  563. ciphersFollower := make([]byte, dbSize*16)
  564. for i := 0; i < dbSize; i++ {
  565. _, err := followerConnection.Read(ciphersFollower[i*16:])
  566. if err != nil {
  567. panic(err)
  568. }
  569. }
  570. //put in ciphers from follower
  571. for i := 0; i < dbSize; i++ {
  572. C.putCipher(1, C.int(i), (*C.uchar)(&ciphersFollower[i*16]))
  573. }
  574. //decrypt each row
  575. for i := 0; i < dbSize; i++ {
  576. C.decryptRow(C.int(i), (*C.uchar)(&tmpdb[i][0]), (*C.uchar)(&tmpdbLeader[i][0]), (*C.uchar)(&tmpdbFollower[i][0]), (*C.uchar)(&seedLeader[0]), (*C.uchar)(&seedFollower[0]))
  577. }
  578. var tweets []lib.Tweet
  579. var currentPublisherAmount float64
  580. var collisions float64
  581. for i := 0; i < dbSize; i++ {
  582. //discard cover message
  583. if tmpdb[i][1] == 0 {
  584. continue
  585. //collision
  586. } else if -1 == strings.Index(string(tmpdb[i]), ";;") {
  587. currentPublisherAmount++
  588. currentPublisherAmount++
  589. collisions++
  590. continue
  591. } else {
  592. currentPublisherAmount++
  593. //reconstruct tweet
  594. var position int = 0
  595. var topics []string
  596. var topic string
  597. var text string
  598. for _, letter := range tmpdb[i] {
  599. if string(letter) == ";" {
  600. if topic != "" {
  601. topics = append(topics, topic)
  602. topic = ""
  603. }
  604. position++
  605. } else {
  606. if position == 0 {
  607. if string(letter) == "," {
  608. topics = append(topics, topic)
  609. topic = ""
  610. } else {
  611. //if topics are
  612. //int
  613. //topic = topic + fmt.Sprint(int(letter))
  614. //string
  615. topic = topic + string(letter)
  616. }
  617. } else if position == 1 {
  618. text = text + string(letter)
  619. }
  620. }
  621. }
  622. tweet := lib.Tweet{"", -1, topics, text, round}
  623. if text != "" {
  624. tweets = append(tweets, tweet)
  625. } else {
  626. //this is a odd(number) way collisions
  627. collisions++
  628. }
  629. }
  630. }
  631. collisionCounter = append(collisionCounter, collisions)
  632. log.Println("Collision percentage this round", collisions/dbWriteSize, "dbWriteSize", dbWriteSize)
  633. lib.NewEntries(tweets, 0)
  634. C.resetDb()
  635. //calculates the publisherAverage over the last publisherRounds rounds
  636. index := round % publisherRounds
  637. publisherHistory[index] = int(currentPublisherAmount)
  638. log.Println("currentPublisherAmount", currentPublisherAmount, "publisher percentage", currentPublisherAmount/clientsConnected)
  639. var publisherAmount int
  640. for _, num := range publisherHistory {
  641. publisherAmount += num
  642. }
  643. publisherAverage := 0
  644. if round < publisherRounds {
  645. publisherAverage = publisherAmount / round
  646. } else {
  647. publisherAverage = publisherAmount / publisherRounds
  648. }
  649. //calculates the dbWriteSize for this round
  650. dbWriteSize = math.Ceil(19.5 * float64(publisherAverage))
  651. if dbWriteSize < minDBWriteSize {
  652. dbWriteSize = minDBWriteSize
  653. }
  654. //writes dbWriteSize of current round to follower
  655. writeTo(followerConnection, intToByte(int(dbWriteSize)))
  656. lib.CleanUpdbR(round)
  657. }
  658. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  659. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex) {
  660. gotClient := make([]byte, 1)
  661. gotClient[0] = 0
  662. //wait until time is up
  663. for len(phase3Channel) == 0 {
  664. if time.Since(startTimeRound) > maxTimePerRound*2 {
  665. //tells follower that this worker is done
  666. writeToWError(followerConnection, gotClient, nil, 0)
  667. wg.Done()
  668. return
  669. }
  670. time.Sleep(1 * time.Second)
  671. }
  672. for clientConnection := range phase3Channel {
  673. clientsServedPhase3[round] = clientsServedPhase3[round] + 1
  674. if clientsServedPhase3[round]%1000 == 0 {
  675. fmt.Println("clientsServedPhase3", clientsServedPhase3[round])
  676. fmt.Println("timeTaken", time.Since(startPhase3).Seconds())
  677. }
  678. gotClient[0] = 1
  679. //tells follower that this worker got a clientConnection
  680. writeToWError(followerConnection, gotClient, nil, 0)
  681. //tells client current phase
  682. errorBool := writeToWError(clientConnection, phase, followerConnection, 2)
  683. if errorBool {
  684. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  685. if contBool {
  686. continue
  687. } else {
  688. return
  689. }
  690. }
  691. /*
  692. possible Values
  693. 0 : new client
  694. leader expects sharedSecrets, expects pirQuery
  695. 1 : update needed
  696. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  697. 2 : no update needed
  698. nothing
  699. */
  700. subPhase := make([]byte, 1)
  701. //gets the data for the current client
  702. m.RLock()
  703. var clientKeys = clientData[clientConnection.RemoteAddr()]
  704. m.RUnlock()
  705. var roundsParticipating = clientKeys.roundsParticipating
  706. //client participates for the first time
  707. if roundsParticipating == 0 {
  708. subPhase[0] = 0
  709. } else if roundsParticipating%roundsBeforeUpdate == 0 {
  710. subPhase[0] = 1
  711. } else {
  712. subPhase[0] = 2
  713. }
  714. //tells client what leader expects
  715. errorBool = writeToWError(clientConnection, subPhase, followerConnection, 2)
  716. if errorBool {
  717. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  718. if contBool {
  719. continue
  720. } else {
  721. return
  722. }
  723. }
  724. //tells follower what will happen
  725. writeToWError(followerConnection, subPhase, nil, 0)
  726. //sends clients publicKey so follower knows which client is being served
  727. writeTo(followerConnection, clientKeys.PublicKey[:])
  728. //increases rounds participating for client
  729. clientKeys.roundsParticipating = roundsParticipating + 1
  730. //declaring variables here to prevent dupclicates later
  731. m.RLock()
  732. var sharedSecret [32]byte = clientData[clientConnection.RemoteAddr()].SharedSecret
  733. m.RUnlock()
  734. if subPhase[0] == 0 {
  735. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  736. if errorBool {
  737. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  738. if contBool {
  739. continue
  740. } else {
  741. return
  742. }
  743. }
  744. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  745. if errorBool {
  746. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  747. if contBool {
  748. continue
  749. } else {
  750. return
  751. }
  752. }
  753. } else if subPhase[0] == 1 {
  754. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  755. if errorBool {
  756. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  757. if contBool {
  758. continue
  759. } else {
  760. return
  761. }
  762. }
  763. //updates sharedSecret
  764. sharedSecret = sha256.Sum256(sharedSecret[:])
  765. clientKeys.SharedSecret = sharedSecret
  766. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  767. if errorBool {
  768. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  769. if contBool {
  770. continue
  771. } else {
  772. return
  773. }
  774. }
  775. }
  776. errorBool = getSendTweets(clientKeys, nil, clientConnection, followerConnection)
  777. if errorBool {
  778. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  779. if contBool {
  780. continue
  781. } else {
  782. return
  783. }
  784. }
  785. wantsArchive, errorBool := readFrom(clientConnection, 1, followerConnection, 2)
  786. if errorBool {
  787. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  788. if contBool {
  789. continue
  790. } else {
  791. return
  792. }
  793. }
  794. writeToWError(followerConnection, wantsArchive, nil, 0)
  795. if wantsArchive[0] == 1 && archiveTopicAmount > 0 {
  796. _, archiveQuerys, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, -1, false)
  797. if errorBool {
  798. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  799. if contBool {
  800. continue
  801. } else {
  802. return
  803. }
  804. }
  805. errorBool = getSendTweets(clientKeys, archiveQuerys, clientConnection, followerConnection)
  806. if errorBool {
  807. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  808. if contBool {
  809. continue
  810. } else {
  811. return
  812. }
  813. }
  814. }
  815. //saves all changes for client
  816. m.Lock()
  817. clientData[clientConnection.RemoteAddr()] = clientKeys
  818. m.Unlock()
  819. phase1Channel <- clientConnection
  820. for {
  821. if time.Since(startTimeRound) < 2*maxTimePerRound {
  822. //this worker handles the next client
  823. if len(phase3Channel) > 0 {
  824. break
  825. //this worker waits for next client
  826. } else {
  827. time.Sleep(1 * time.Second)
  828. }
  829. //times up
  830. } else {
  831. //tells follower that this worker is done
  832. gotClient[0] = 0
  833. writeToWError(followerConnection, gotClient, nil, 0)
  834. wg.Done()
  835. return
  836. }
  837. }
  838. }
  839. }
  840. //returns true if there is another client
  841. func handleClientDC(wg *sync.WaitGroup, followerConnection net.Conn, channel chan net.Conn) bool {
  842. //loop that waits for new client or leaves phase1 if time is up
  843. for {
  844. if time.Since(startTimeRound) < maxTimePerRound {
  845. //this worker handles the next client
  846. if len(channel) > 0 {
  847. return true
  848. //this worker waits for next client
  849. } else {
  850. time.Sleep(1 * time.Second)
  851. }
  852. //times up
  853. } else {
  854. //tells follower that this worker is done
  855. gotClient := make([]byte, 1)
  856. gotClient[0] = 0
  857. writeTo(followerConnection, gotClient)
  858. wg.Done()
  859. return false
  860. }
  861. }
  862. }
  863. func createVirtualAddresses() []int {
  864. //array will be filled with unique random ascending values
  865. //adapted from: https://stackoverflow.com/questions/20039025/java-array-of-unique-randomly-generated-integers
  866. //+extraPositions to have a position to evaluate each received message
  867. arraySize := int(dbWriteSize) + extraPositions
  868. var maxInt int = int(math.Pow(2, 31))
  869. virtualAddresses := make([]int, arraySize)
  870. for i := 0; i < arraySize; i++ {
  871. virtualAddresses[i] = mr.Intn(maxInt)
  872. for j := 0; j < i; j++ {
  873. if virtualAddresses[i] == virtualAddresses[j] {
  874. i--
  875. break
  876. }
  877. }
  878. }
  879. sort.Ints(virtualAddresses)
  880. return virtualAddresses
  881. }
  882. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, clientConnection, followerConnection net.Conn) bool {
  883. //xores all requested addresses into virtuallAddress
  884. virtualAddress := make([]byte, 4)
  885. for index, num := range pirQuery {
  886. if num == 1 {
  887. currentAddress := intToByte(virtualAddresses[index])
  888. for i := 0; i < 4; i++ {
  889. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  890. }
  891. }
  892. }
  893. //xores the sharedSecret
  894. for i := 0; i < 4; i++ {
  895. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  896. }
  897. virtualAddressFollower, _ := readFrom(followerConnection, 4, nil, 0)
  898. //xores the data from follower
  899. for i := 0; i < 4; i++ {
  900. virtualAddress[i] = virtualAddress[i] ^ virtualAddressFollower[i]
  901. }
  902. errorBool := writeToWError(clientConnection, virtualAddress, followerConnection, 5)
  903. return errorBool
  904. }
  905. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, clientConnection, followerConnection net.Conn) bool {
  906. tmpNeededSubscriptions := neededSubscriptions
  907. if tmpNeededSubscriptions > topicAmount {
  908. tmpNeededSubscriptions = topicAmount
  909. }
  910. if archiveQuerys != nil {
  911. tmpNeededSubscriptions = len(archiveQuerys)
  912. if tmpNeededSubscriptions > archiveTopicAmount {
  913. tmpNeededSubscriptions = archiveTopicAmount
  914. }
  915. }
  916. tweets := make([][]byte, tmpNeededSubscriptions)
  917. for i := 0; i < tmpNeededSubscriptions; i++ {
  918. //gets all requested tweets
  919. if archiveQuerys == nil {
  920. tweets[i] = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0, *clientKeys.PublicKey)
  921. } else {
  922. tweets[i] = lib.GetTweets(archiveQuerys[i], dataLength, 1, *clientKeys.PublicKey)
  923. }
  924. //expand sharedSecret so it is of right length
  925. expandBy := len(tweets[i]) / 32
  926. var expandedSharedSecret []byte
  927. for i := 0; i < expandBy; i++ {
  928. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  929. }
  930. //Xor's sharedSecret with all tweets
  931. lib.Xor(expandedSharedSecret[:], tweets[i])
  932. blockLength := len(tweets[i])
  933. receivedTweets, _ := readFrom(followerConnection, blockLength, nil, 0)
  934. lib.Xor(receivedTweets, tweets[i])
  935. }
  936. //sends tweets to client
  937. for i := 0; i < tmpNeededSubscriptions; i++ {
  938. tweetsLengthBytes := intToByte(len(tweets[i]))
  939. if firstTweetSend && archiveQuerys == nil {
  940. firstTweetSend = false
  941. log.Println("sending", len(tweets[0]), "bytes of data")
  942. }
  943. errorBool := writeToWError(clientConnection, tweetsLengthBytes, followerConnection, 2)
  944. if errorBool {
  945. return true
  946. }
  947. errorBool = writeToWError(clientConnection, tweets[i], followerConnection, 2)
  948. if errorBool {
  949. return true
  950. }
  951. }
  952. return false
  953. }
  954. func handlePirQuery(clientKeys clientKeys, clientConnection net.Conn, followerConnection net.Conn, subPhase int, doAuditing bool) (clientKeys, [][]byte, bool) {
  955. clientPublicKey := clientKeys.PublicKey
  956. //gets the msg length
  957. msgLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  958. if errorBool {
  959. return clientKeys, nil, true
  960. }
  961. msgLength := byteToInt(msgLengthBytes)
  962. //gets the leader box
  963. leaderBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  964. if errorBool {
  965. return clientKeys, nil, true
  966. }
  967. //gets the follower box
  968. followerBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  969. if errorBool {
  970. return clientKeys, nil, true
  971. }
  972. tmpNeededSubscriptions := neededSubscriptions
  973. if tmpNeededSubscriptions > topicAmount {
  974. tmpNeededSubscriptions = topicAmount
  975. }
  976. tmpTopicAmount := topicAmount
  977. if subPhase == -1 {
  978. archiveNeededSubscriptions, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  979. if errorBool {
  980. return clientKeys, nil, true
  981. }
  982. writeToWError(followerConnection, archiveNeededSubscriptions, nil, 0)
  983. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  984. tmpTopicAmount = archiveTopicAmount
  985. if tmpNeededSubscriptions > archiveTopicAmount {
  986. tmpNeededSubscriptions = archiveTopicAmount
  987. }
  988. }
  989. if doAuditing {
  990. tmpNeededSubscriptions = 1
  991. tmpTopicAmount = int(dbWriteSize)
  992. }
  993. //send length to follower
  994. writeToWError(followerConnection, msgLengthBytes, nil, 0)
  995. //send box to follower
  996. writeToWError(followerConnection, followerBox, nil, 0)
  997. var decryptNonce [24]byte
  998. copy(decryptNonce[:], leaderBox[:24])
  999. decrypted, ok := box.Open(nil, leaderBox[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  1000. if !ok {
  1001. fmt.Println("pirQuery decryption not ok")
  1002. return clientKeys, nil, true
  1003. }
  1004. //if sharedSecret is send
  1005. if subPhase == 0 {
  1006. var tmpSharedSecret [32]byte
  1007. for index := 0; index < 32; index++ {
  1008. tmpSharedSecret[index] = decrypted[index]
  1009. }
  1010. clientKeys.SharedSecret = tmpSharedSecret
  1011. decrypted = decrypted[32:]
  1012. }
  1013. if doAuditing {
  1014. result := make([][]byte, 1)
  1015. result[0] = decrypted
  1016. return clientKeys, result, false
  1017. }
  1018. if subPhase == -1 {
  1019. }
  1020. //transforms byteArray to ints of wanted topics
  1021. pirQueryFlattened := decrypted
  1022. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  1023. for i := range pirQuerys {
  1024. pirQuerys[i] = make([]byte, tmpTopicAmount)
  1025. }
  1026. for i := 0; i < tmpNeededSubscriptions; i++ {
  1027. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  1028. }
  1029. //sets the pirQuery for the client in case whe are not archiving, and not Auditing
  1030. if subPhase != -1 {
  1031. clientKeys.PirQuery = pirQuerys
  1032. }
  1033. return clientKeys, pirQuerys, false
  1034. }
  1035. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  1036. var topics []string
  1037. var topic string
  1038. var position int = 0
  1039. for _, letter := range topicsAsBytes {
  1040. if string(letter) == "," {
  1041. topics[position] = topic
  1042. topic = ""
  1043. position++
  1044. } else {
  1045. topic = topic + string(letter)
  1046. }
  1047. }
  1048. return topics
  1049. }
  1050. func byteToInt(myBytes []byte) (x int) {
  1051. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  1052. return
  1053. }
  1054. //returns true if error occured
  1055. func sendTopicLists(clientConnection, followerConnection net.Conn, setup bool) bool {
  1056. for i := 0; i < 2; i++ {
  1057. var topicList []byte
  1058. if i == 0 {
  1059. topicList, topicAmount = lib.GetTopicList(i)
  1060. } else {
  1061. topicList, archiveTopicAmount = lib.GetTopicList(i)
  1062. }
  1063. topicListLengthBytes := intToByte(len(topicList))
  1064. if !setup {
  1065. err := writeToWError(clientConnection, topicListLengthBytes, followerConnection, 5)
  1066. if err {
  1067. return true
  1068. }
  1069. err = writeToWError(clientConnection, topicList, followerConnection, 5)
  1070. if err {
  1071. return true
  1072. }
  1073. } else {
  1074. _, err := clientConnection.Write(topicListLengthBytes)
  1075. if err != nil {
  1076. return true
  1077. }
  1078. _, err = clientConnection.Write(topicList)
  1079. if err != nil {
  1080. return true
  1081. }
  1082. }
  1083. }
  1084. return false
  1085. }
  1086. //sends the array to the connection
  1087. func writeTo(connection net.Conn, array []byte) {
  1088. remainingLength := len(array)
  1089. for remainingLength > 0 {
  1090. if remainingLength >= mtu {
  1091. _, err := connection.Write(array[:mtu])
  1092. if err != nil {
  1093. panic(err)
  1094. }
  1095. array = array[mtu:]
  1096. remainingLength -= mtu
  1097. } else {
  1098. _, err := connection.Write(array)
  1099. if err != nil {
  1100. panic(err)
  1101. }
  1102. remainingLength = 0
  1103. }
  1104. }
  1105. }
  1106. func writeToWError(connection net.Conn, array []byte, followerConnection net.Conn, size int) bool {
  1107. if connection.RemoteAddr().String() == follower {
  1108. arrayWError := make([]byte, 1)
  1109. arrayWError = append(arrayWError, array[:]...)
  1110. remainingLength := len(arrayWError)
  1111. for remainingLength > 0 {
  1112. if remainingLength >= mtu {
  1113. _, err := connection.Write(arrayWError[:mtu])
  1114. if err != nil {
  1115. return handleError(connection, followerConnection, size, err)
  1116. }
  1117. arrayWError = arrayWError[mtu:]
  1118. remainingLength -= mtu
  1119. } else {
  1120. _, err := connection.Write(arrayWError)
  1121. if err != nil {
  1122. return handleError(connection, followerConnection, size, err)
  1123. }
  1124. remainingLength = 0
  1125. }
  1126. }
  1127. } else {
  1128. remainingLength := len(array)
  1129. for remainingLength > 0 {
  1130. if remainingLength >= mtu {
  1131. _, err := connection.Write(array[:mtu])
  1132. if err != nil {
  1133. return handleError(connection, followerConnection, size, err)
  1134. }
  1135. array = array[mtu:]
  1136. remainingLength -= mtu
  1137. } else {
  1138. _, err := connection.Write(array)
  1139. if err != nil {
  1140. return handleError(connection, followerConnection, size, err)
  1141. }
  1142. remainingLength = 0
  1143. }
  1144. }
  1145. }
  1146. return false
  1147. }
  1148. func handleError(connection, followerConnection net.Conn, size int, err error) bool {
  1149. if err != nil {
  1150. //lets follower know that client has disconnected unexpectedly
  1151. if connection.RemoteAddr().String() != follower {
  1152. if size > mtu {
  1153. fmt.Println("have a look here")
  1154. }
  1155. fmt.Println("handleError", err)
  1156. array := make([]byte, size)
  1157. array[0] = 1
  1158. _, err = followerConnection.Write(array)
  1159. if err != nil {
  1160. panic(err)
  1161. }
  1162. return true
  1163. } else {
  1164. panic(err)
  1165. }
  1166. }
  1167. return false
  1168. }
  1169. //reads an array which is returned and of size "size" from the connection
  1170. //returns true if error occured
  1171. func readFrom(connection net.Conn, size int, followerConnection net.Conn, sizeError int) ([]byte, bool) {
  1172. var array []byte
  1173. remainingSize := size
  1174. for remainingSize > 0 {
  1175. var err error
  1176. toAppend := make([]byte, mtu)
  1177. if remainingSize > mtu {
  1178. _, err = connection.Read(toAppend)
  1179. array = append(array, toAppend...)
  1180. remainingSize -= mtu
  1181. } else {
  1182. _, err = connection.Read(toAppend[:remainingSize])
  1183. array = append(array, toAppend[:remainingSize]...)
  1184. remainingSize = 0
  1185. }
  1186. if err != nil {
  1187. //lets follower know that client has disconnected unexpectedly
  1188. if connection.RemoteAddr().String() != follower {
  1189. fmt.Println(err)
  1190. array := make([]byte, sizeError)
  1191. array[0] = 1
  1192. _, err = followerConnection.Write(array)
  1193. if err != nil {
  1194. panic(err)
  1195. }
  1196. return nil, true
  1197. } else {
  1198. panic(err)
  1199. }
  1200. }
  1201. }
  1202. return array, false
  1203. }
  1204. func intToByte(myInt int) (retBytes []byte) {
  1205. retBytes = make([]byte, 4)
  1206. retBytes[3] = byte((myInt >> 24) & 0xff)
  1207. retBytes[2] = byte((myInt >> 16) & 0xff)
  1208. retBytes[1] = byte((myInt >> 8) & 0xff)
  1209. retBytes[0] = byte(myInt & 0xff)
  1210. return
  1211. }