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 minDBWriteSize = 1000
  56. const numClients = 500
  57. var dbWriteSize float64 = numClients * 19.5
  58. //this is the number of positions for auditing
  59. var extraPositions int = 2
  60. var collisionCounter []float64
  61. var clientsConnected float64
  62. var maxTimePerRound time.Duration = 1000 * time.Second
  63. //counts the number of rounds
  64. var round int
  65. var clientsServedPhase1 []int
  66. var clientsServedPhase3 []int
  67. var startPhase1 time.Time
  68. var startPhase2 time.Time
  69. var startPhase3 time.Time
  70. //only prints auditing time for one client per round
  71. var firstAuditPrint bool
  72. var auditingStart time.Time
  73. var auditingEnd time.Time
  74. var startTime time.Time
  75. var startTimeRound time.Time
  76. //channel for goroutine communication with clients
  77. var phase1Channel = make(chan net.Conn, maxNumberOfClients)
  78. var phase3Channel = make(chan net.Conn, maxNumberOfClients)
  79. //variables for calculating the dbWrite size
  80. const publisherRounds int = 10
  81. var publisherAmount float64
  82. var publisherHistory [publisherRounds]int
  83. var firstTweetSend bool
  84. func main() {
  85. f, err := os.OpenFile("evalData", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  86. if err != nil {
  87. log.Fatalf("error opening file: %v", err)
  88. }
  89. defer f.Close()
  90. log.SetOutput(f)
  91. log.Println("roundsBeforeUpdate", roundsBeforeUpdate)
  92. log.Println("neededSubscriptions", neededSubscriptions)
  93. log.Println("dataLength", dataLength)
  94. log.Println("maxTimePerRound~", maxTimePerRound*3)
  95. log.Println("extraPositions", extraPositions)
  96. log.Println("numClients", numClients)
  97. log.Println("Archiving is done every 24h, no Clients wants Archive")
  98. //prevents race conditions for wrtiting
  99. m := &sync.RWMutex{}
  100. startTime = time.Now()
  101. clientsServedPhase1 = make([]int, 1000)
  102. clientsServedPhase3 = make([]int, 1000)
  103. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  104. if err != nil {
  105. panic(err)
  106. }
  107. //why is this neccessary?
  108. leaderPrivateKey = generatedPrivateKey
  109. leaderPublicKey = generatedPublicKey
  110. C.initializeServer(C.int(numThreads))
  111. //calls follower for setup
  112. conf := &tls.Config{
  113. InsecureSkipVerify: true,
  114. }
  115. followerConnection, err := tls.Dial("tcp", follower, conf)
  116. if err != nil {
  117. panic(err)
  118. }
  119. followerConnection.SetDeadline(time.Time{})
  120. //receives follower publicKey
  121. var tmpFollowerPubKey [32]byte
  122. _, err = followerConnection.Read(tmpFollowerPubKey[:])
  123. if err != nil {
  124. panic(err)
  125. }
  126. followerPublicKey = &tmpFollowerPubKey
  127. //send publicKey to follower
  128. writeTo(followerConnection, leaderPublicKey[:])
  129. writeTo(followerConnection, intToByte(neededSubscriptions))
  130. writeTo(followerConnection, intToByte(int(dbWriteSize)))
  131. //goroutine for accepting new clients
  132. go func() {
  133. leaderConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  134. if err != nil {
  135. panic(err)
  136. }
  137. // Generate a pem block with the private key
  138. keyPem := pem.EncodeToMemory(&pem.Block{
  139. Type: "RSA PRIVATE KEY",
  140. Bytes: x509.MarshalPKCS1PrivateKey(leaderConnectionPrivateKey),
  141. })
  142. tml := x509.Certificate{
  143. // you can add any attr that you need
  144. NotBefore: time.Now(),
  145. NotAfter: time.Now().AddDate(5, 0, 0),
  146. // you have to generate a different serial number each execution
  147. SerialNumber: big.NewInt(123123),
  148. Subject: pkix.Name{
  149. CommonName: "New Name",
  150. Organization: []string{"New Org."},
  151. },
  152. BasicConstraintsValid: true,
  153. }
  154. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &leaderConnectionPrivateKey.PublicKey, leaderConnectionPrivateKey)
  155. if err != nil {
  156. panic(err)
  157. }
  158. // Generate a pem block with the certificate
  159. certPem := pem.EncodeToMemory(&pem.Block{
  160. Type: "CERTIFICATE",
  161. Bytes: cert,
  162. })
  163. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  164. if err != nil {
  165. panic(err)
  166. }
  167. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  168. //listens for clients
  169. lnClients, err := tls.Listen("tcp", ":4441", config)
  170. if err != nil {
  171. panic(err)
  172. }
  173. defer lnClients.Close()
  174. for {
  175. clientConnection, err := lnClients.Accept()
  176. if err != nil {
  177. fmt.Println("Client connection error 1", err)
  178. clientConnection.Close()
  179. break
  180. }
  181. clientConnection.SetDeadline(time.Time{})
  182. //sends topicList so client can participate in phase 3 asap
  183. errorBool := sendTopicLists(clientConnection, followerConnection, true)
  184. if errorBool {
  185. break
  186. }
  187. //send leader publicKey
  188. _, err = clientConnection.Write(leaderPublicKey[:])
  189. if err != nil {
  190. fmt.Println("Client connection error 2", err)
  191. clientConnection.Close()
  192. break
  193. }
  194. //send follower publicKey
  195. _, err = clientConnection.Write(followerPublicKey[:])
  196. if err != nil {
  197. fmt.Println("Client connection error 3", err)
  198. clientConnection.Close()
  199. break
  200. }
  201. var clientPublicKey *[32]byte
  202. var tmpClientPublicKey [32]byte
  203. //gets publicKey from client
  204. _, err = clientConnection.Read(tmpClientPublicKey[:])
  205. if err != nil {
  206. fmt.Println("Client connection error 4", err)
  207. clientConnection.Close()
  208. break
  209. }
  210. _, err = clientConnection.Write(intToByte(neededSubscriptions))
  211. if err != nil {
  212. fmt.Println("Client connection error 5", err)
  213. clientConnection.Close()
  214. break
  215. }
  216. _, err = clientConnection.Write(intToByte(int(startTime.Unix())))
  217. if err != nil {
  218. fmt.Println("Client connection error 6", err)
  219. clientConnection.Close()
  220. break
  221. }
  222. clientPublicKey = &tmpClientPublicKey
  223. //this is the key for map(client data)
  224. remoteAddress := clientConnection.RemoteAddr()
  225. //pirQuery will be added in phase 3
  226. //bs! only want to set roundsParticipating and answerAmount to 0, mb there is a better way
  227. //will work for now
  228. var emptyArray [32]byte
  229. var emptyByteArray [][]byte
  230. keys := clientKeys{0, clientPublicKey, emptyArray, emptyByteArray}
  231. m.Lock()
  232. clientData[remoteAddress] = keys
  233. m.Unlock()
  234. phase1Channel <- clientConnection
  235. clientsConnected++
  236. }
  237. }()
  238. wg := &sync.WaitGroup{}
  239. //the current phase
  240. phase := make([]byte, 1)
  241. for {
  242. startPhase1 = time.Now()
  243. startTimeRound = time.Now()
  244. firstAuditPrint = true
  245. phase[0] = 1
  246. round++
  247. fmt.Println("clientsServedPhase1", clientsServedPhase1[round-1])
  248. fmt.Println("clientsServedPhase3", clientsServedPhase3[round-1])
  249. log.Println()
  250. log.Println("Phase 1 Round", round)
  251. log.Println()
  252. bytesSaved := lib.GetBytesSaved()
  253. log.Println("bytesSaved Percentage", bytesSaved)
  254. //creates a new write Db for this round
  255. for i := 0; i < int(dbWriteSize); i++ {
  256. C.createDb(C.int(1), C.int(dataLength))
  257. }
  258. //creates a new db containing virtual addresses for auditing
  259. virtualAddresses := createVirtualAddresses()
  260. //send all virtualAddresses to follower
  261. for i := 0; i <= int(dbWriteSize); i++ {
  262. writeTo(followerConnection, intToByte(virtualAddresses[i]))
  263. }
  264. //moves all clients to phase1
  265. if len(phase3Channel) > 0 {
  266. for client := range phase3Channel {
  267. phase1Channel <- client
  268. if len(phase3Channel) == 0 {
  269. break
  270. }
  271. }
  272. }
  273. for id := 0; id < numThreads; id++ {
  274. wg.Add(1)
  275. followerConnection, err := tls.Dial("tcp", follower, conf)
  276. if err != nil {
  277. panic(err)
  278. }
  279. followerConnection.SetDeadline(time.Time{})
  280. go phase1(id, phase, followerConnection, wg, m, virtualAddresses)
  281. }
  282. wg.Wait()
  283. log.Println("fullDurationPhase1", time.Since(startPhase1).Seconds())
  284. log.Println("fullAuditingDuration~", auditingEnd.Sub(auditingStart).Seconds()*clientsConnected)
  285. log.Println("auditingPercentage", (auditingEnd.Sub(auditingStart).Seconds()*clientsConnected)/(time.Since(startPhase1).Seconds()))
  286. //Phase 2
  287. startPhase2 = time.Now()
  288. followerConnection, err := tls.Dial("tcp", follower, conf)
  289. if err != nil {
  290. panic(err)
  291. }
  292. followerConnection.SetDeadline(time.Time{})
  293. phase2(followerConnection)
  294. log.Println("fullDurationPhase2", time.Since(startPhase2).Seconds())
  295. //Phase 3
  296. //moves all clients to phase3
  297. if len(phase1Channel) > 0 {
  298. for client := range phase1Channel {
  299. phase3Channel <- client
  300. if len(phase1Channel) == 0 {
  301. break
  302. }
  303. }
  304. }
  305. startPhase3 = time.Now()
  306. //no tweets -> continue to phase 1 and mb get tweets
  307. topicList, topicAmount = lib.GetTopicList(0)
  308. if len(topicList) == 0 {
  309. continue
  310. }
  311. firstTweetSend = true
  312. phase[0] = 3
  313. startTimeRound = time.Now()
  314. for id := 0; id < numThreads; id++ {
  315. wg.Add(1)
  316. followerConnection, err := tls.Dial("tcp", follower, conf)
  317. if err != nil {
  318. panic(err)
  319. }
  320. followerConnection.SetDeadline(time.Time{})
  321. go phase3(id, phase, followerConnection, wg, m)
  322. }
  323. wg.Wait()
  324. log.Println("fullDurationPhase3", time.Since(startPhase3).Seconds())
  325. lib.CleanUpdbR(round)
  326. }
  327. }
  328. func phase1(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex, virtualAddresses []int) {
  329. roundAsBytes := intToByte(round)
  330. gotClient := make([]byte, 1)
  331. gotClient[0] = 0
  332. //wait until time is up
  333. for len(phase1Channel) == 0 {
  334. if time.Since(startTimeRound) > maxTimePerRound {
  335. //tells follower that this worker is done
  336. writeTo(followerConnection, gotClient)
  337. wg.Done()
  338. return
  339. }
  340. time.Sleep(1 * time.Second)
  341. }
  342. for clientConnection := range phase1Channel {
  343. clientsServedPhase1[round] = clientsServedPhase1[round] + 1
  344. gotClient[0] = 1
  345. //tells follower that this worker got a clientConnection
  346. writeTo(followerConnection, gotClient)
  347. //sends clients publicKey to follower
  348. m.RLock()
  349. clientPublicKey := clientData[clientConnection.RemoteAddr()].PublicKey
  350. m.RUnlock()
  351. writeTo(followerConnection, clientPublicKey[:])
  352. //setup the worker-specific db
  353. dbSize := int(C.dbSize)
  354. db := make([][]byte, dbSize)
  355. for i := 0; i < dbSize; i++ {
  356. db[i] = make([]byte, int(C.db[i].dataSize))
  357. }
  358. //tells client that phase 1 has begun
  359. errorBool := writeToWError(clientConnection, phase, followerConnection, 5)
  360. if errorBool {
  361. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  362. if contBool {
  363. continue
  364. } else {
  365. return
  366. }
  367. }
  368. //tells client current dbWriteSize
  369. errorBool = writeToWError(clientConnection, intToByte(int(dbWriteSize)), followerConnection, 5)
  370. if errorBool {
  371. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  372. if contBool {
  373. continue
  374. } else {
  375. return
  376. }
  377. }
  378. //tells client current round
  379. errorBool = writeToWError(clientConnection, roundAsBytes, followerConnection, 5)
  380. if errorBool {
  381. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  382. if contBool {
  383. continue
  384. } else {
  385. return
  386. }
  387. }
  388. //begin auditing
  389. if id == 0 && firstAuditPrint {
  390. auditingStart = time.Now()
  391. }
  392. m.RLock()
  393. var clientKeys = clientData[clientConnection.RemoteAddr()]
  394. m.RUnlock()
  395. clientKeys, pirQuery, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, 0, true)
  396. if errorBool {
  397. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  398. if contBool {
  399. continue
  400. } else {
  401. return
  402. }
  403. }
  404. errorBool = getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, clientConnection, followerConnection)
  405. if errorBool {
  406. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  407. if contBool {
  408. continue
  409. } else {
  410. return
  411. }
  412. }
  413. if id == 0 && firstAuditPrint {
  414. firstAuditPrint = false
  415. auditingEnd = time.Now()
  416. log.Println("Auditing duration", time.Since(auditingStart).Seconds(), "numVirtualAddresses", len(virtualAddresses))
  417. }
  418. m.Lock()
  419. clientData[clientConnection.RemoteAddr()] = clientKeys
  420. m.Unlock()
  421. //accept dpfQuery from client
  422. dpfLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  423. if errorBool {
  424. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  425. if contBool {
  426. continue
  427. } else {
  428. return
  429. }
  430. }
  431. dpfLength := byteToInt(dpfLengthBytes)
  432. dpfQueryAEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  433. if errorBool {
  434. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  435. if contBool {
  436. continue
  437. } else {
  438. return
  439. }
  440. }
  441. dpfQueryBEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  442. if errorBool {
  443. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  444. if contBool {
  445. continue
  446. } else {
  447. return
  448. }
  449. }
  450. writeToWError(followerConnection, dpfLengthBytes, nil, 0)
  451. writeToWError(followerConnection, dpfQueryBEncrypted, nil, 0)
  452. //decrypt dpfQueryA for sorting into db
  453. var decryptNonce [24]byte
  454. copy(decryptNonce[:], dpfQueryAEncrypted[:24])
  455. dpfQueryA, ok := box.Open(nil, dpfQueryAEncrypted[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  456. if !ok {
  457. panic("dpfQueryA decryption not ok")
  458. }
  459. ds := int(C.db[0].dataSize)
  460. dataShareLeader := make([]byte, ds)
  461. pos := C.getUint128_t(C.int(virtualAddresses[int(dbWriteSize)]))
  462. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShareLeader[0]))
  463. dataShareFollower, _ := readFrom(followerConnection, ds, nil, 0)
  464. writeToWError(followerConnection, dataShareLeader, nil, 0)
  465. auditXOR := make([]byte, ds)
  466. passedAudit := true
  467. for i := 0; i < ds; i++ {
  468. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  469. //client tried to write to a position that is not a virtuallAddress
  470. if auditXOR[i] != 0 {
  471. clientConnection.Close()
  472. passedAudit = false
  473. }
  474. }
  475. if passedAudit {
  476. //run dpf, xor into local db
  477. for i := 0; i < dbSize; i++ {
  478. ds := int(C.db[i].dataSize)
  479. dataShare := make([]byte, ds)
  480. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  481. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  482. for j := 0; j < ds; j++ {
  483. db[i][j] = db[i][j] ^ dataShare[j]
  484. }
  485. }
  486. //xor the worker's DB into the main DB
  487. for i := 0; i < dbSize; i++ {
  488. m.Lock()
  489. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  490. m.Unlock()
  491. }
  492. phase3Channel <- clientConnection
  493. }
  494. //loop that waits for new client or leaves phase1 if time is up
  495. //todo! remove && len(phase1Channel) > 0
  496. for {
  497. if time.Since(startTimeRound) < maxTimePerRound && len(phase1Channel) > 0 {
  498. //this worker handles the next client
  499. if len(phase1Channel) > 0 {
  500. break
  501. //this worker waits for next client
  502. } else {
  503. time.Sleep(1 * time.Second)
  504. }
  505. //times up
  506. } else {
  507. //tells follower that this worker is done
  508. gotClient[0] = 0
  509. writeTo(followerConnection, gotClient)
  510. wg.Done()
  511. return
  512. }
  513. }
  514. }
  515. }
  516. func phase2(followerConnection net.Conn) {
  517. //gets current seed
  518. seedLeader := make([]byte, 16)
  519. C.readSeed((*C.uchar)(&seedLeader[0]))
  520. //get data
  521. dbSize := int(C.dbSize)
  522. tmpdbLeader := make([][]byte, dbSize)
  523. for i := range tmpdbLeader {
  524. tmpdbLeader[i] = make([]byte, dataLength)
  525. }
  526. for i := 0; i < dbSize; i++ {
  527. C.readData(C.int(i), (*C.uchar)(&tmpdbLeader[i][0]))
  528. }
  529. //writes seed to follower
  530. writeTo(followerConnection, seedLeader)
  531. //write data to follower
  532. //this is surely inefficent
  533. for i := 0; i < dbSize; i++ {
  534. writeTo(followerConnection, tmpdbLeader[i])
  535. }
  536. //receive seed from follower
  537. seedFollower, _ := readFrom(followerConnection, 16, nil, 0)
  538. //receive data from follower
  539. tmpdbFollower := make([][]byte, dbSize)
  540. for i := range tmpdbFollower {
  541. tmpdbFollower[i] = make([]byte, dataLength)
  542. }
  543. for i := 0; i < dbSize; i++ {
  544. tmpdbFollower[i], _ = readFrom(followerConnection, dataLength, nil, 0)
  545. }
  546. //put together the db
  547. tmpdb := make([][]byte, dbSize)
  548. for i := range tmpdb {
  549. tmpdb[i] = make([]byte, dataLength)
  550. }
  551. //get own Ciphers
  552. ciphersLeader := make([]*C.uchar, dbSize)
  553. for i := 0; i < dbSize; i++ {
  554. ciphersLeader[i] = (*C.uchar)(C.malloc(16))
  555. }
  556. for i := 0; i < dbSize; i++ {
  557. C.getCipher(1, C.int(i), ciphersLeader[i])
  558. }
  559. //send own Ciphers to follower
  560. for i := 0; i < dbSize; i++ {
  561. writeTo(followerConnection, C.GoBytes(unsafe.Pointer(ciphersLeader[i]), 16))
  562. }
  563. //receive ciphers from follower
  564. ciphersFollower := make([]byte, dbSize*16)
  565. for i := 0; i < dbSize; i++ {
  566. _, err := followerConnection.Read(ciphersFollower[i*16:])
  567. if err != nil {
  568. panic(err)
  569. }
  570. }
  571. //put in ciphers from follower
  572. for i := 0; i < dbSize; i++ {
  573. C.putCipher(1, C.int(i), (*C.uchar)(&ciphersFollower[i*16]))
  574. }
  575. //decrypt each row
  576. for i := 0; i < dbSize; i++ {
  577. 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]))
  578. }
  579. var tweets []lib.Tweet
  580. var currentPublisherAmount float64
  581. var collisions float64
  582. for i := 0; i < dbSize; i++ {
  583. //discard cover message
  584. if tmpdb[i][1] == 0 {
  585. continue
  586. //collision
  587. } else if -1 == strings.Index(string(tmpdb[i]), ";;") {
  588. currentPublisherAmount++
  589. currentPublisherAmount++
  590. collisions++
  591. continue
  592. } else {
  593. currentPublisherAmount++
  594. //reconstruct tweet
  595. var position int = 0
  596. var topics []string
  597. var topic string
  598. var text string
  599. for _, letter := range tmpdb[i] {
  600. if string(letter) == ";" {
  601. if topic != "" {
  602. topics = append(topics, topic)
  603. topic = ""
  604. }
  605. position++
  606. } else {
  607. if position == 0 {
  608. if string(letter) == "," {
  609. topics = append(topics, topic)
  610. topic = ""
  611. } else {
  612. //if topics are
  613. //int
  614. //topic = topic + fmt.Sprint(int(letter))
  615. //string
  616. topic = topic + string(letter)
  617. }
  618. } else if position == 1 {
  619. text = text + string(letter)
  620. }
  621. }
  622. }
  623. tweet := lib.Tweet{"", -1, topics, text, round}
  624. if text != "" {
  625. tweets = append(tweets, tweet)
  626. } else {
  627. //this is a odd(number) way collisions
  628. collisions++
  629. }
  630. }
  631. }
  632. collisionCounter = append(collisionCounter, collisions)
  633. log.Println("Collision percentage this round", collisions/dbWriteSize, "dbWriteSize", dbWriteSize)
  634. lib.NewEntries(tweets, 0)
  635. C.resetDb()
  636. //calculates the publisherAverage over the last publisherRounds rounds
  637. index := round % publisherRounds
  638. publisherHistory[index] = int(currentPublisherAmount)
  639. log.Println("currentPublisherAmount", currentPublisherAmount, "publisher percentage", currentPublisherAmount/clientsConnected)
  640. var publisherAmount int
  641. for _, num := range publisherHistory {
  642. publisherAmount += num
  643. }
  644. publisherAverage := 0
  645. if round < publisherRounds {
  646. publisherAverage = publisherAmount / round
  647. } else {
  648. publisherAverage = publisherAmount / publisherRounds
  649. }
  650. //calculates the dbWriteSize for this round
  651. dbWriteSize = math.Ceil(19.5 * float64(publisherAverage))
  652. if dbWriteSize < minDBWriteSize {
  653. dbWriteSize = minDBWriteSize
  654. }
  655. //writes dbWriteSize of current round to follower
  656. writeTo(followerConnection, intToByte(int(dbWriteSize)))
  657. lib.CleanUpdbR(round)
  658. }
  659. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  660. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex) {
  661. gotClient := make([]byte, 1)
  662. gotClient[0] = 0
  663. //wait until time is up
  664. for len(phase3Channel) == 0 {
  665. if time.Since(startTimeRound) > maxTimePerRound*2 {
  666. //tells follower that this worker is done
  667. writeToWError(followerConnection, gotClient, nil, 0)
  668. wg.Done()
  669. return
  670. }
  671. time.Sleep(1 * time.Second)
  672. }
  673. for clientConnection := range phase3Channel {
  674. clientsServedPhase3[round] = clientsServedPhase3[round] + 1
  675. if clientsServedPhase3[round]%1000 == 0 {
  676. fmt.Println("clientsServedPhase3", clientsServedPhase3[round])
  677. fmt.Println("timeTaken", time.Since(startPhase3).Seconds())
  678. }
  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. }