leader.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  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. log.Println("bytesSaved Percentage", bytesSaved)
  252. firstAuditPrint = true
  253. //creates a new write Db for this round
  254. for i := 0; i < int(dbWriteSize); i++ {
  255. C.createDb(C.int(1), C.int(dataLength))
  256. }
  257. //creates a new db containing virtual addresses for auditing
  258. virtualAddresses := createVirtualAddresses()
  259. //send all virtualAddresses to follower
  260. for i := 0; i <= int(dbWriteSize); i++ {
  261. writeTo(followerConnection, intToByte(virtualAddresses[i]))
  262. }
  263. //moves all clients to phase1
  264. if len(phase3Channel) > 0 {
  265. for client := range phase3Channel {
  266. phase1Channel <- client
  267. if len(phase3Channel) == 0 {
  268. break
  269. }
  270. }
  271. }
  272. for id := 0; id < numThreads; id++ {
  273. wg.Add(1)
  274. followerConnection, err := tls.Dial("tcp", follower, conf)
  275. if err != nil {
  276. panic(err)
  277. }
  278. followerConnection.SetDeadline(time.Time{})
  279. go phase1(id, phase, followerConnection, wg, m, virtualAddresses)
  280. }
  281. wg.Wait()
  282. //log.Println("fullDurationPhase1", time.Since(startPhase1).Seconds())
  283. log.Println("fullAuditingDuration~", auditingEnd.Sub(auditingStart).Seconds()*clientsConnected)
  284. log.Println("auditingPercentage", (auditingEnd.Sub(auditingStart).Seconds()*clientsConnected)/(time.Since(startPhase1).Seconds()))
  285. //Phase 2
  286. startPhase2 = time.Now()
  287. followerConnection, err := tls.Dial("tcp", follower, conf)
  288. if err != nil {
  289. panic(err)
  290. }
  291. followerConnection.SetDeadline(time.Time{})
  292. phase2(followerConnection)
  293. //log.Println("fullDurationPhase2", time.Since(startPhase2).Seconds())
  294. //Phase 3
  295. //moves all clients to phase3
  296. if len(phase1Channel) > 0 {
  297. for client := range phase1Channel {
  298. phase3Channel <- client
  299. if len(phase1Channel) == 0 {
  300. break
  301. }
  302. }
  303. }
  304. startPhase3 = time.Now()
  305. //no tweets -> continue to phase 1 and mb get tweets
  306. topicList, topicAmount = lib.GetTopicList(0)
  307. if len(topicList) == 0 {
  308. continue
  309. }
  310. firstTweetSend = true
  311. phase[0] = 3
  312. startTimeRound = time.Now()
  313. for id := 0; id < numThreads; id++ {
  314. wg.Add(1)
  315. followerConnection, err := tls.Dial("tcp", follower, conf)
  316. if err != nil {
  317. panic(err)
  318. }
  319. followerConnection.SetDeadline(time.Time{})
  320. go phase3(id, phase, followerConnection, wg, m)
  321. }
  322. wg.Wait()
  323. log.Println("fullDurationPhase3", time.Since(startPhase3).Seconds())
  324. lib.CleanUpdbR(round)
  325. }
  326. }
  327. func phase1(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex, virtualAddresses []int) {
  328. roundAsBytes := intToByte(round)
  329. gotClient := make([]byte, 1)
  330. gotClient[0] = 0
  331. //wait until time is up
  332. for len(phase1Channel) == 0 {
  333. if time.Since(startTimeRound) > maxTimePerRound {
  334. //tells follower that this worker is done
  335. writeTo(followerConnection, gotClient)
  336. wg.Done()
  337. return
  338. }
  339. time.Sleep(1 * time.Second)
  340. }
  341. for clientConnection := range phase1Channel {
  342. clientsServedPhase1[round] = clientsServedPhase1[round] + 1
  343. gotClient[0] = 1
  344. //tells follower that this worker got a clientConnection
  345. writeTo(followerConnection, gotClient)
  346. //sends clients publicKey to follower
  347. m.RLock()
  348. clientPublicKey := clientData[clientConnection.RemoteAddr()].PublicKey
  349. m.RUnlock()
  350. writeTo(followerConnection, clientPublicKey[:])
  351. //setup the worker-specific db
  352. dbSize := int(C.dbSize)
  353. db := make([][]byte, dbSize)
  354. for i := 0; i < dbSize; i++ {
  355. db[i] = make([]byte, int(C.db[i].dataSize))
  356. }
  357. //tells client that phase 1 has begun
  358. errorBool := writeToWError(clientConnection, phase, followerConnection, 5)
  359. if errorBool {
  360. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  361. if contBool {
  362. continue
  363. } else {
  364. return
  365. }
  366. }
  367. //tells client current dbWriteSize
  368. errorBool = writeToWError(clientConnection, intToByte(int(dbWriteSize)), followerConnection, 5)
  369. if errorBool {
  370. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  371. if contBool {
  372. continue
  373. } else {
  374. return
  375. }
  376. }
  377. //tells client current round
  378. errorBool = writeToWError(clientConnection, roundAsBytes, followerConnection, 5)
  379. if errorBool {
  380. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  381. if contBool {
  382. continue
  383. } else {
  384. return
  385. }
  386. }
  387. //begin auditing
  388. if id == 0 && firstAuditPrint {
  389. auditingStart = time.Now()
  390. }
  391. m.RLock()
  392. var clientKeys = clientData[clientConnection.RemoteAddr()]
  393. m.RUnlock()
  394. clientKeys, pirQuery, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, 0, true)
  395. if errorBool {
  396. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  397. if contBool {
  398. continue
  399. } else {
  400. return
  401. }
  402. }
  403. errorBool = getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, clientConnection, followerConnection)
  404. if errorBool {
  405. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  406. if contBool {
  407. continue
  408. } else {
  409. return
  410. }
  411. }
  412. if id == 0 && firstAuditPrint {
  413. firstAuditPrint = false
  414. auditingEnd = time.Now()
  415. log.Println("Auditing duration", time.Since(auditingStart).Seconds(), "numVirtualAddresses", len(virtualAddresses))
  416. }
  417. m.Lock()
  418. clientData[clientConnection.RemoteAddr()] = clientKeys
  419. m.Unlock()
  420. //accept dpfQuery from client
  421. dpfLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  422. if errorBool {
  423. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  424. if contBool {
  425. continue
  426. } else {
  427. return
  428. }
  429. }
  430. dpfLength := byteToInt(dpfLengthBytes)
  431. dpfQueryAEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  432. if errorBool {
  433. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  434. if contBool {
  435. continue
  436. } else {
  437. return
  438. }
  439. }
  440. dpfQueryBEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  441. if errorBool {
  442. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  443. if contBool {
  444. continue
  445. } else {
  446. return
  447. }
  448. }
  449. writeToWError(followerConnection, dpfLengthBytes, nil, 0)
  450. writeToWError(followerConnection, dpfQueryBEncrypted, nil, 0)
  451. //decrypt dpfQueryA for sorting into db
  452. var decryptNonce [24]byte
  453. copy(decryptNonce[:], dpfQueryAEncrypted[:24])
  454. dpfQueryA, ok := box.Open(nil, dpfQueryAEncrypted[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  455. if !ok {
  456. panic("dpfQueryA decryption not ok")
  457. }
  458. ds := int(C.db[0].dataSize)
  459. dataShareLeader := make([]byte, ds)
  460. pos := C.getUint128_t(C.int(virtualAddresses[int(dbWriteSize)]))
  461. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShareLeader[0]))
  462. dataShareFollower, _ := readFrom(followerConnection, ds, nil, 0)
  463. writeToWError(followerConnection, dataShareLeader, nil, 0)
  464. auditXOR := make([]byte, ds)
  465. passedAudit := true
  466. for i := 0; i < ds; i++ {
  467. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  468. //client tried to write to a position that is not a virtuallAddress
  469. if auditXOR[i] != 0 {
  470. clientConnection.Close()
  471. passedAudit = false
  472. }
  473. }
  474. if passedAudit {
  475. //run dpf, xor into local db
  476. for i := 0; i < dbSize; i++ {
  477. ds := int(C.db[i].dataSize)
  478. dataShare := make([]byte, ds)
  479. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  480. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  481. for j := 0; j < ds; j++ {
  482. db[i][j] = db[i][j] ^ dataShare[j]
  483. }
  484. }
  485. //xor the worker's DB into the main DB
  486. for i := 0; i < dbSize; i++ {
  487. m.Lock()
  488. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  489. m.Unlock()
  490. }
  491. phase3Channel <- clientConnection
  492. }
  493. //loop that waits for new client or leaves phase1 if time is up
  494. for {
  495. if time.Since(startTimeRound) < maxTimePerRound {
  496. //this worker handles the next client
  497. if len(phase1Channel) > 0 {
  498. break
  499. //this worker waits for next client
  500. } else {
  501. time.Sleep(1 * time.Second)
  502. }
  503. //times up
  504. } else {
  505. //tells follower that this worker is done
  506. gotClient[0] = 0
  507. writeTo(followerConnection, gotClient)
  508. wg.Done()
  509. return
  510. }
  511. }
  512. }
  513. }
  514. func phase2(followerConnection net.Conn) {
  515. //gets current seed
  516. seedLeader := make([]byte, 16)
  517. C.readSeed((*C.uchar)(&seedLeader[0]))
  518. //get data
  519. dbSize := int(C.dbSize)
  520. tmpdbLeader := make([][]byte, dbSize)
  521. for i := range tmpdbLeader {
  522. tmpdbLeader[i] = make([]byte, dataLength)
  523. }
  524. for i := 0; i < dbSize; i++ {
  525. C.readData(C.int(i), (*C.uchar)(&tmpdbLeader[i][0]))
  526. }
  527. //writes seed to follower
  528. writeTo(followerConnection, seedLeader)
  529. //write data to follower
  530. //this is surely inefficent
  531. for i := 0; i < dbSize; i++ {
  532. writeTo(followerConnection, tmpdbLeader[i])
  533. }
  534. //receive seed from follower
  535. seedFollower, _ := readFrom(followerConnection, 16, nil, 0)
  536. //receive data from follower
  537. tmpdbFollower := make([][]byte, dbSize)
  538. for i := range tmpdbFollower {
  539. tmpdbFollower[i] = make([]byte, dataLength)
  540. }
  541. for i := 0; i < dbSize; i++ {
  542. tmpdbFollower[i], _ = readFrom(followerConnection, dataLength, nil, 0)
  543. }
  544. //put together the db
  545. tmpdb := make([][]byte, dbSize)
  546. for i := range tmpdb {
  547. tmpdb[i] = make([]byte, dataLength)
  548. }
  549. //get own Ciphers
  550. ciphersLeader := make([]*C.uchar, dbSize)
  551. for i := 0; i < dbSize; i++ {
  552. ciphersLeader[i] = (*C.uchar)(C.malloc(16))
  553. }
  554. for i := 0; i < dbSize; i++ {
  555. C.getCipher(1, C.int(i), ciphersLeader[i])
  556. }
  557. //send own Ciphers to follower
  558. for i := 0; i < dbSize; i++ {
  559. writeTo(followerConnection, C.GoBytes(unsafe.Pointer(ciphersLeader[i]), 16))
  560. }
  561. //receive ciphers from follower
  562. ciphersFollower := make([]byte, dbSize*16)
  563. for i := 0; i < dbSize; i++ {
  564. _, err := followerConnection.Read(ciphersFollower[i*16:])
  565. if err != nil {
  566. panic(err)
  567. }
  568. }
  569. //put in ciphers from follower
  570. for i := 0; i < dbSize; i++ {
  571. C.putCipher(1, C.int(i), (*C.uchar)(&ciphersFollower[i*16]))
  572. }
  573. //decrypt each row
  574. for i := 0; i < dbSize; i++ {
  575. 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]))
  576. }
  577. var tweets []lib.Tweet
  578. var currentPublisherAmount float64
  579. var collisions float64
  580. for i := 0; i < dbSize; i++ {
  581. //discard cover message
  582. if tmpdb[i][1] == 0 {
  583. continue
  584. //collision
  585. } else if -1 == strings.Index(string(tmpdb[i]), ";;") {
  586. currentPublisherAmount++
  587. currentPublisherAmount++
  588. collisions++
  589. continue
  590. } else {
  591. currentPublisherAmount++
  592. //reconstruct tweet
  593. var position int = 0
  594. var topics []string
  595. var topic string
  596. var text string
  597. for _, letter := range tmpdb[i] {
  598. if string(letter) == ";" {
  599. if topic != "" {
  600. topics = append(topics, topic)
  601. topic = ""
  602. }
  603. position++
  604. } else {
  605. if position == 0 {
  606. if string(letter) == "," {
  607. topics = append(topics, topic)
  608. topic = ""
  609. } else {
  610. //if topics are
  611. //int
  612. //topic = topic + fmt.Sprint(int(letter))
  613. //string
  614. topic = topic + string(letter)
  615. }
  616. } else if position == 1 {
  617. text = text + string(letter)
  618. }
  619. }
  620. }
  621. tweet := lib.Tweet{"", -1, topics, text, round}
  622. if text != "" {
  623. tweets = append(tweets, tweet)
  624. } else {
  625. //this is a odd(number) way collisions
  626. collisions++
  627. }
  628. }
  629. }
  630. collisionCounter = append(collisionCounter, collisions)
  631. log.Println("Collision percentage this round", collisions/dbWriteSize, "dbWriteSize", dbWriteSize)
  632. lib.NewEntries(tweets, 0)
  633. C.resetDb()
  634. //calculates the publisherAverage over the last publisherRounds rounds
  635. index := round % publisherRounds
  636. publisherHistory[index] = int(currentPublisherAmount)
  637. log.Println("currentPublisherAmount", currentPublisherAmount, "publisher percentage", currentPublisherAmount/clientsConnected)
  638. var publisherAmount int
  639. for _, num := range publisherHistory {
  640. publisherAmount += num
  641. }
  642. publisherAverage := 0
  643. if round < publisherRounds {
  644. publisherAverage = publisherAmount / round
  645. } else {
  646. publisherAverage = publisherAmount / publisherRounds
  647. }
  648. //calculates the dbWriteSize for this round
  649. dbWriteSize = math.Ceil(19.5 * float64(publisherAverage))
  650. if dbWriteSize < minDBWriteSize {
  651. dbWriteSize = minDBWriteSize
  652. }
  653. //writes dbWriteSize of current round to follower
  654. writeTo(followerConnection, intToByte(int(dbWriteSize)))
  655. lib.CleanUpdbR(round)
  656. }
  657. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  658. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex) {
  659. gotClient := make([]byte, 1)
  660. gotClient[0] = 0
  661. //wait until time is up
  662. for len(phase3Channel) == 0 {
  663. if time.Since(startTimeRound) > maxTimePerRound*2 {
  664. //tells follower that this worker is done
  665. writeToWError(followerConnection, gotClient, nil, 0)
  666. wg.Done()
  667. return
  668. }
  669. time.Sleep(1 * time.Second)
  670. }
  671. for clientConnection := range phase3Channel {
  672. clientsServedPhase3[round] = clientsServedPhase3[round] + 1
  673. if clientsServedPhase3[round]%1000 == 0 {
  674. fmt.Println("clientsServedPhase3", clientsServedPhase3[round])
  675. fmt.Println("timeTaken", time.Since(startPhase3).Seconds())
  676. }
  677. gotClient[0] = 1
  678. //tells follower that this worker got a clientConnection
  679. writeToWError(followerConnection, gotClient, nil, 0)
  680. //tells client current phase
  681. errorBool := writeToWError(clientConnection, phase, followerConnection, 2)
  682. if errorBool {
  683. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  684. if contBool {
  685. continue
  686. } else {
  687. return
  688. }
  689. }
  690. /*
  691. possible Values
  692. 0 : new client
  693. leader expects sharedSecrets, expects pirQuery
  694. 1 : update needed
  695. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  696. 2 : no update needed
  697. nothing
  698. */
  699. subPhase := make([]byte, 1)
  700. //gets the data for the current client
  701. m.RLock()
  702. var clientKeys = clientData[clientConnection.RemoteAddr()]
  703. m.RUnlock()
  704. var roundsParticipating = clientKeys.roundsParticipating
  705. //client participates for the first time
  706. if roundsParticipating == 0 {
  707. subPhase[0] = 0
  708. } else if roundsParticipating%roundsBeforeUpdate == 0 {
  709. subPhase[0] = 1
  710. } else {
  711. subPhase[0] = 2
  712. }
  713. //tells client what leader expects
  714. errorBool = writeToWError(clientConnection, subPhase, followerConnection, 2)
  715. if errorBool {
  716. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  717. if contBool {
  718. continue
  719. } else {
  720. return
  721. }
  722. }
  723. //tells follower what will happen
  724. writeToWError(followerConnection, subPhase, nil, 0)
  725. //sends clients publicKey so follower knows which client is being served
  726. writeTo(followerConnection, clientKeys.PublicKey[:])
  727. //increases rounds participating for client
  728. clientKeys.roundsParticipating = roundsParticipating + 1
  729. //declaring variables here to prevent dupclicates later
  730. m.RLock()
  731. var sharedSecret [32]byte = clientData[clientConnection.RemoteAddr()].SharedSecret
  732. m.RUnlock()
  733. if subPhase[0] == 0 {
  734. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  735. if errorBool {
  736. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  737. if contBool {
  738. continue
  739. } else {
  740. return
  741. }
  742. }
  743. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  744. if errorBool {
  745. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  746. if contBool {
  747. continue
  748. } else {
  749. return
  750. }
  751. }
  752. } else if subPhase[0] == 1 {
  753. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  754. if errorBool {
  755. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  756. if contBool {
  757. continue
  758. } else {
  759. return
  760. }
  761. }
  762. //updates sharedSecret
  763. sharedSecret = sha256.Sum256(sharedSecret[:])
  764. clientKeys.SharedSecret = sharedSecret
  765. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  766. if errorBool {
  767. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  768. if contBool {
  769. continue
  770. } else {
  771. return
  772. }
  773. }
  774. }
  775. errorBool = getSendTweets(clientKeys, nil, clientConnection, followerConnection)
  776. if errorBool {
  777. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  778. if contBool {
  779. continue
  780. } else {
  781. return
  782. }
  783. }
  784. wantsArchive, errorBool := readFrom(clientConnection, 1, followerConnection, 2)
  785. if errorBool {
  786. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  787. if contBool {
  788. continue
  789. } else {
  790. return
  791. }
  792. }
  793. writeToWError(followerConnection, wantsArchive, nil, 0)
  794. if wantsArchive[0] == 1 && archiveTopicAmount > 0 {
  795. _, archiveQuerys, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, -1, false)
  796. if errorBool {
  797. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  798. if contBool {
  799. continue
  800. } else {
  801. return
  802. }
  803. }
  804. errorBool = getSendTweets(clientKeys, archiveQuerys, clientConnection, followerConnection)
  805. if errorBool {
  806. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  807. if contBool {
  808. continue
  809. } else {
  810. return
  811. }
  812. }
  813. }
  814. //saves all changes for client
  815. m.Lock()
  816. clientData[clientConnection.RemoteAddr()] = clientKeys
  817. m.Unlock()
  818. phase1Channel <- clientConnection
  819. for {
  820. if time.Since(startTimeRound) < 2*maxTimePerRound {
  821. //this worker handles the next client
  822. if len(phase3Channel) > 0 {
  823. break
  824. //this worker waits for next client
  825. } else {
  826. time.Sleep(1 * time.Second)
  827. }
  828. //times up
  829. } else {
  830. //tells follower that this worker is done
  831. gotClient[0] = 0
  832. writeToWError(followerConnection, gotClient, nil, 0)
  833. wg.Done()
  834. return
  835. }
  836. }
  837. }
  838. }
  839. //returns true if there is another client
  840. func handleClientDC(wg *sync.WaitGroup, followerConnection net.Conn, channel chan net.Conn) bool {
  841. //loop that waits for new client or leaves phase1 if time is up
  842. for {
  843. if time.Since(startTimeRound) < maxTimePerRound {
  844. //this worker handles the next client
  845. if len(channel) > 0 {
  846. return true
  847. //this worker waits for next client
  848. } else {
  849. time.Sleep(1 * time.Second)
  850. }
  851. //times up
  852. } else {
  853. //tells follower that this worker is done
  854. gotClient := make([]byte, 1)
  855. gotClient[0] = 0
  856. writeTo(followerConnection, gotClient)
  857. wg.Done()
  858. return false
  859. }
  860. }
  861. }
  862. func createVirtualAddresses() []int {
  863. //array will be filled with unique random ascending values
  864. //adapted from: https://stackoverflow.com/questions/20039025/java-array-of-unique-randomly-generated-integers
  865. //+extraPositions to have a position to evaluate each received message
  866. arraySize := int(dbWriteSize) + extraPositions
  867. var maxInt int = int(math.Pow(2, 31))
  868. virtualAddresses := make([]int, arraySize)
  869. for i := 0; i < arraySize; i++ {
  870. virtualAddresses[i] = mr.Intn(maxInt)
  871. for j := 0; j < i; j++ {
  872. if virtualAddresses[i] == virtualAddresses[j] {
  873. i--
  874. break
  875. }
  876. }
  877. }
  878. sort.Ints(virtualAddresses)
  879. return virtualAddresses
  880. }
  881. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, clientConnection, followerConnection net.Conn) bool {
  882. //xores all requested addresses into virtuallAddress
  883. virtualAddress := make([]byte, 4)
  884. for index, num := range pirQuery {
  885. if num == 1 {
  886. currentAddress := intToByte(virtualAddresses[index])
  887. for i := 0; i < 4; i++ {
  888. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  889. }
  890. }
  891. }
  892. //xores the sharedSecret
  893. for i := 0; i < 4; i++ {
  894. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  895. }
  896. virtualAddressFollower, _ := readFrom(followerConnection, 4, nil, 0)
  897. //xores the data from follower
  898. for i := 0; i < 4; i++ {
  899. virtualAddress[i] = virtualAddress[i] ^ virtualAddressFollower[i]
  900. }
  901. errorBool := writeToWError(clientConnection, virtualAddress, followerConnection, 5)
  902. return errorBool
  903. }
  904. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, clientConnection, followerConnection net.Conn) bool {
  905. tmpNeededSubscriptions := neededSubscriptions
  906. if tmpNeededSubscriptions > topicAmount {
  907. tmpNeededSubscriptions = topicAmount
  908. }
  909. if archiveQuerys != nil {
  910. tmpNeededSubscriptions = len(archiveQuerys)
  911. if tmpNeededSubscriptions > archiveTopicAmount {
  912. tmpNeededSubscriptions = archiveTopicAmount
  913. }
  914. }
  915. tweets := make([][]byte, tmpNeededSubscriptions)
  916. for i := 0; i < tmpNeededSubscriptions; i++ {
  917. //gets all requested tweets
  918. if archiveQuerys == nil {
  919. tweets[i] = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0, *clientKeys.PublicKey)
  920. } else {
  921. tweets[i] = lib.GetTweets(archiveQuerys[i], dataLength, 1, *clientKeys.PublicKey)
  922. }
  923. //expand sharedSecret so it is of right length
  924. expandBy := len(tweets[i]) / 32
  925. var expandedSharedSecret []byte
  926. for i := 0; i < expandBy; i++ {
  927. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  928. }
  929. //Xor's sharedSecret with all tweets
  930. lib.Xor(expandedSharedSecret[:], tweets[i])
  931. blockLength := len(tweets[i])
  932. receivedTweets, _ := readFrom(followerConnection, blockLength, nil, 0)
  933. lib.Xor(receivedTweets, tweets[i])
  934. }
  935. //sends tweets to client
  936. for i := 0; i < tmpNeededSubscriptions; i++ {
  937. tweetsLengthBytes := intToByte(len(tweets[i]))
  938. if firstTweetSend && archiveQuerys == nil {
  939. firstTweetSend = false
  940. log.Println("sending", len(tweets[0]), "bytes of data")
  941. }
  942. errorBool := writeToWError(clientConnection, tweetsLengthBytes, followerConnection, 2)
  943. if errorBool {
  944. return true
  945. }
  946. errorBool = writeToWError(clientConnection, tweets[i], followerConnection, 2)
  947. if errorBool {
  948. return true
  949. }
  950. }
  951. return false
  952. }
  953. func handlePirQuery(clientKeys clientKeys, clientConnection net.Conn, followerConnection net.Conn, subPhase int, doAuditing bool) (clientKeys, [][]byte, bool) {
  954. clientPublicKey := clientKeys.PublicKey
  955. //gets the msg length
  956. msgLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  957. if errorBool {
  958. return clientKeys, nil, true
  959. }
  960. msgLength := byteToInt(msgLengthBytes)
  961. //gets the leader box
  962. leaderBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  963. if errorBool {
  964. return clientKeys, nil, true
  965. }
  966. //gets the follower box
  967. followerBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  968. if errorBool {
  969. return clientKeys, nil, true
  970. }
  971. tmpNeededSubscriptions := neededSubscriptions
  972. if tmpNeededSubscriptions > topicAmount {
  973. tmpNeededSubscriptions = topicAmount
  974. }
  975. tmpTopicAmount := topicAmount
  976. if subPhase == -1 {
  977. archiveNeededSubscriptions, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  978. if errorBool {
  979. return clientKeys, nil, true
  980. }
  981. writeToWError(followerConnection, archiveNeededSubscriptions, nil, 0)
  982. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  983. tmpTopicAmount = archiveTopicAmount
  984. if tmpNeededSubscriptions > archiveTopicAmount {
  985. tmpNeededSubscriptions = archiveTopicAmount
  986. }
  987. }
  988. if doAuditing {
  989. tmpNeededSubscriptions = 1
  990. tmpTopicAmount = int(dbWriteSize)
  991. }
  992. //send length to follower
  993. writeToWError(followerConnection, msgLengthBytes, nil, 0)
  994. //send box to follower
  995. writeToWError(followerConnection, followerBox, nil, 0)
  996. var decryptNonce [24]byte
  997. copy(decryptNonce[:], leaderBox[:24])
  998. decrypted, ok := box.Open(nil, leaderBox[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  999. if !ok {
  1000. fmt.Println("pirQuery decryption not ok")
  1001. return clientKeys, nil, true
  1002. }
  1003. //if sharedSecret is send
  1004. if subPhase == 0 {
  1005. var tmpSharedSecret [32]byte
  1006. for index := 0; index < 32; index++ {
  1007. tmpSharedSecret[index] = decrypted[index]
  1008. }
  1009. clientKeys.SharedSecret = tmpSharedSecret
  1010. decrypted = decrypted[32:]
  1011. }
  1012. if doAuditing {
  1013. result := make([][]byte, 1)
  1014. result[0] = decrypted
  1015. return clientKeys, result, false
  1016. }
  1017. if subPhase == -1 {
  1018. }
  1019. //transforms byteArray to ints of wanted topics
  1020. pirQueryFlattened := decrypted
  1021. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  1022. for i := range pirQuerys {
  1023. pirQuerys[i] = make([]byte, tmpTopicAmount)
  1024. }
  1025. for i := 0; i < tmpNeededSubscriptions; i++ {
  1026. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  1027. }
  1028. //sets the pirQuery for the client in case whe are not archiving, and not Auditing
  1029. if subPhase != -1 {
  1030. clientKeys.PirQuery = pirQuerys
  1031. }
  1032. return clientKeys, pirQuerys, false
  1033. }
  1034. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  1035. var topics []string
  1036. var topic string
  1037. var position int = 0
  1038. for _, letter := range topicsAsBytes {
  1039. if string(letter) == "," {
  1040. topics[position] = topic
  1041. topic = ""
  1042. position++
  1043. } else {
  1044. topic = topic + string(letter)
  1045. }
  1046. }
  1047. return topics
  1048. }
  1049. func byteToInt(myBytes []byte) (x int) {
  1050. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  1051. return
  1052. }
  1053. //returns true if error occured
  1054. func sendTopicLists(clientConnection, followerConnection net.Conn, setup bool) bool {
  1055. for i := 0; i < 2; i++ {
  1056. var topicList []byte
  1057. if i == 0 {
  1058. topicList, topicAmount = lib.GetTopicList(i)
  1059. } else {
  1060. topicList, archiveTopicAmount = lib.GetTopicList(i)
  1061. }
  1062. topicListLengthBytes := intToByte(len(topicList))
  1063. if !setup {
  1064. err := writeToWError(clientConnection, topicListLengthBytes, followerConnection, 5)
  1065. if err {
  1066. return true
  1067. }
  1068. err = writeToWError(clientConnection, topicList, followerConnection, 5)
  1069. if err {
  1070. return true
  1071. }
  1072. } else {
  1073. _, err := clientConnection.Write(topicListLengthBytes)
  1074. if err != nil {
  1075. return true
  1076. }
  1077. _, err = clientConnection.Write(topicList)
  1078. if err != nil {
  1079. return true
  1080. }
  1081. }
  1082. }
  1083. return false
  1084. }
  1085. //sends the array to the connection
  1086. func writeTo(connection net.Conn, array []byte) {
  1087. remainingLength := len(array)
  1088. for remainingLength > 0 {
  1089. if remainingLength >= mtu {
  1090. _, err := connection.Write(array[:mtu])
  1091. if err != nil {
  1092. panic(err)
  1093. }
  1094. array = array[mtu:]
  1095. remainingLength -= mtu
  1096. } else {
  1097. _, err := connection.Write(array)
  1098. if err != nil {
  1099. panic(err)
  1100. }
  1101. remainingLength = 0
  1102. }
  1103. }
  1104. }
  1105. func writeToWError(connection net.Conn, array []byte, followerConnection net.Conn, size int) bool {
  1106. if connection.RemoteAddr().String() == follower {
  1107. arrayWError := make([]byte, 1)
  1108. arrayWError = append(arrayWError, array[:]...)
  1109. remainingLength := len(arrayWError)
  1110. for remainingLength > 0 {
  1111. if remainingLength >= mtu {
  1112. _, err := connection.Write(arrayWError[:mtu])
  1113. if err != nil {
  1114. return handleError(connection, followerConnection, size, err)
  1115. }
  1116. arrayWError = arrayWError[mtu:]
  1117. remainingLength -= mtu
  1118. } else {
  1119. _, err := connection.Write(arrayWError)
  1120. if err != nil {
  1121. return handleError(connection, followerConnection, size, err)
  1122. }
  1123. remainingLength = 0
  1124. }
  1125. }
  1126. } else {
  1127. remainingLength := len(array)
  1128. for remainingLength > 0 {
  1129. if remainingLength >= mtu {
  1130. _, err := connection.Write(array[:mtu])
  1131. if err != nil {
  1132. return handleError(connection, followerConnection, size, err)
  1133. }
  1134. array = array[mtu:]
  1135. remainingLength -= mtu
  1136. } else {
  1137. _, err := connection.Write(array)
  1138. if err != nil {
  1139. return handleError(connection, followerConnection, size, err)
  1140. }
  1141. remainingLength = 0
  1142. }
  1143. }
  1144. }
  1145. return false
  1146. }
  1147. func handleError(connection, followerConnection net.Conn, size int, err error) bool {
  1148. if err != nil {
  1149. //lets follower know that client has disconnected unexpectedly
  1150. if connection.RemoteAddr().String() != follower {
  1151. if size > mtu {
  1152. fmt.Println("have a look here")
  1153. }
  1154. fmt.Println("handleError", err)
  1155. array := make([]byte, size)
  1156. array[0] = 1
  1157. _, err = followerConnection.Write(array)
  1158. if err != nil {
  1159. panic(err)
  1160. }
  1161. return true
  1162. } else {
  1163. panic(err)
  1164. }
  1165. }
  1166. return false
  1167. }
  1168. //reads an array which is returned and of size "size" from the connection
  1169. //returns true if error occured
  1170. func readFrom(connection net.Conn, size int, followerConnection net.Conn, sizeError int) ([]byte, bool) {
  1171. var array []byte
  1172. remainingSize := size
  1173. for remainingSize > 0 {
  1174. var err error
  1175. toAppend := make([]byte, mtu)
  1176. if remainingSize > mtu {
  1177. _, err = connection.Read(toAppend)
  1178. array = append(array, toAppend...)
  1179. remainingSize -= mtu
  1180. } else {
  1181. _, err = connection.Read(toAppend[:remainingSize])
  1182. array = append(array, toAppend[:remainingSize]...)
  1183. remainingSize = 0
  1184. }
  1185. if err != nil {
  1186. //lets follower know that client has disconnected unexpectedly
  1187. if connection.RemoteAddr().String() != follower {
  1188. fmt.Println(err)
  1189. array := make([]byte, sizeError)
  1190. array[0] = 1
  1191. _, err = followerConnection.Write(array)
  1192. if err != nil {
  1193. panic(err)
  1194. }
  1195. return nil, true
  1196. } else {
  1197. panic(err)
  1198. }
  1199. }
  1200. }
  1201. return array, false
  1202. }
  1203. func intToByte(myInt int) (retBytes []byte) {
  1204. retBytes = make([]byte, 4)
  1205. retBytes[3] = byte((myInt >> 24) & 0xff)
  1206. retBytes[2] = byte((myInt >> 16) & 0xff)
  1207. retBytes[1] = byte((myInt >> 8) & 0xff)
  1208. retBytes[0] = byte(myInt & 0xff)
  1209. return
  1210. }