leader.go 36 KB

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