follower.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. //sssssssssssssssss
  10. import (
  11. "2PPS/lib"
  12. "crypto/rand"
  13. "crypto/rsa"
  14. "crypto/sha256"
  15. "crypto/tls"
  16. "crypto/x509"
  17. "crypto/x509/pkix"
  18. "encoding/pem"
  19. "fmt"
  20. "math/big"
  21. "net"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. "unsafe"
  27. "golang.org/x/crypto/nacl/box"
  28. )
  29. //this stores all neccessary information for each client
  30. type clientKeys struct {
  31. SharedSecret [32]byte
  32. PirQuery [][]byte
  33. }
  34. //uses clients publicKey as key
  35. var clientData = make(map[[32]byte]clientKeys)
  36. var topicList []byte
  37. var topicAmount int
  38. var followerPrivateKey *[32]byte
  39. var followerPublicKey *[32]byte
  40. var leaderPublicKey *[32]byte
  41. //needs to be changed at leader/follower/client at the same time
  42. const neededSubscriptions = 1
  43. const dataLength = 128
  44. const numThreads = 12
  45. var dbWriteSize int = 100
  46. var maxTimePerRound time.Duration = 5 * time.Second
  47. var round int = 0
  48. var startTime time.Time
  49. var ignoreMe []byte
  50. func main() {
  51. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  52. if err != nil {
  53. panic(err)
  54. }
  55. followerPrivateKey = generatedPrivateKey
  56. followerPublicKey = generatedPublicKey
  57. C.initializeServer(C.int(numThreads))
  58. followerConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  59. if err != nil {
  60. panic(err)
  61. }
  62. // Generate a pem block with the private key
  63. keyPem := pem.EncodeToMemory(&pem.Block{
  64. Type: "RSA PRIVATE KEY",
  65. Bytes: x509.MarshalPKCS1PrivateKey(followerConnectionPrivateKey),
  66. })
  67. tml := x509.Certificate{
  68. // you can add any attr that you need
  69. NotBefore: time.Now(),
  70. NotAfter: time.Now().AddDate(5, 0, 0),
  71. // you have to generate a different serial number each execution
  72. SerialNumber: big.NewInt(123123),
  73. Subject: pkix.Name{
  74. CommonName: "New Name",
  75. Organization: []string{"New Org."},
  76. },
  77. BasicConstraintsValid: true,
  78. }
  79. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &followerConnectionPrivateKey.PublicKey, followerConnectionPrivateKey)
  80. if err != nil {
  81. panic(err)
  82. }
  83. // Generate a pem block with the certificate
  84. certPem := pem.EncodeToMemory(&pem.Block{
  85. Type: "CERTIFICATE",
  86. Bytes: cert,
  87. })
  88. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  89. if err != nil {
  90. panic(err)
  91. }
  92. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  93. fmt.Println("start leader")
  94. //listens for leader
  95. lnLeader, err := tls.Listen("tcp", ":4442", config)
  96. if err != nil {
  97. panic(err)
  98. }
  99. defer lnLeader.Close()
  100. leaderConnection, err := lnLeader.Accept()
  101. if err != nil {
  102. panic(err)
  103. }
  104. //send publicKey to leader
  105. writeTo(leaderConnection, followerPublicKey[:])
  106. //receives leader PublicKey
  107. var tmpLeaderPubKey [32]byte
  108. _, err = leaderConnection.Read(tmpLeaderPubKey[:])
  109. if err != nil {
  110. panic(err)
  111. }
  112. leaderPublicKey = &tmpLeaderPubKey
  113. //setup ends here
  114. //locks access to DB
  115. m := &sync.RWMutex{}
  116. wg := &sync.WaitGroup{}
  117. for {
  118. round++
  119. fmt.Println("Phase 1 Round", round)
  120. //create write db for this round
  121. for i := 0; i < dbWriteSize; i++ {
  122. C.createDb(C.int(0), C.int(dataLength))
  123. }
  124. //receives the virtualAddresses
  125. virtualAddresses := make([]int, dbWriteSize+1)
  126. for i := 0; i <= dbWriteSize; i++ {
  127. virtualAddress := readFrom(leaderConnection, 4)
  128. virtualAddresses[i] = byteToInt(virtualAddress)
  129. }
  130. for i := 0; i < numThreads; i++ {
  131. wg.Add(1)
  132. leaderConnection, err := lnLeader.Accept()
  133. if err != nil {
  134. panic(err)
  135. }
  136. leaderConnection.SetDeadline(time.Time{})
  137. startTime = time.Now()
  138. go phase1(i, leaderConnection, m, wg, virtualAddresses)
  139. }
  140. wg.Wait()
  141. fmt.Println("Phase 2")
  142. leaderConnection, err := lnLeader.Accept()
  143. if err != nil {
  144. panic(err)
  145. }
  146. leaderConnection.SetDeadline(time.Time{})
  147. phase2(leaderConnection)
  148. fmt.Println("Phase 3")
  149. if round == 1 {
  150. //addTestTweets()
  151. }
  152. //no tweets -> continue to phase 1 and mb get tweets
  153. topicList, topicAmount = lib.GetTopicList(0)
  154. if len(topicList) == 0 {
  155. continue
  156. }
  157. for i := 0; i < numThreads; i++ {
  158. wg.Add(1)
  159. leaderConnection, err := lnLeader.Accept()
  160. if err != nil {
  161. panic(err)
  162. }
  163. leaderConnection.SetDeadline(time.Time{})
  164. startTime = time.Now()
  165. go phase3(leaderConnection, wg, m)
  166. }
  167. wg.Wait()
  168. lib.CleanUpdbR(round)
  169. }
  170. }
  171. func phase1(id int, leaderWorkerConnection net.Conn, m *sync.RWMutex, wg *sync.WaitGroup, virtualAddresses []int) {
  172. for {
  173. gotClient := readFrom(leaderWorkerConnection, 1)
  174. //this worker is done
  175. if gotClient[0] == 0 {
  176. wg.Done()
  177. return
  178. }
  179. //setup the worker-specific db
  180. dbSize := int(C.dbSize)
  181. db := make([][]byte, dbSize)
  182. for i := 0; i < dbSize; i++ {
  183. db[i] = make([]byte, int(C.db[i].dataSize))
  184. }
  185. //gets clients publicKey
  186. var clientPublicKey *[32]byte
  187. var tmpClientPublicKey [32]byte
  188. _, err := leaderWorkerConnection.Read(tmpClientPublicKey[:])
  189. if err != nil {
  190. fmt.Println("no error handling")
  191. panic(err)
  192. }
  193. clientPublicKey = &tmpClientPublicKey
  194. m.RLock()
  195. clientKeys := clientData[tmpClientPublicKey]
  196. m.RUnlock()
  197. clientKeys, pirQuery, errorBool := handlePirQuery(clientKeys, leaderWorkerConnection, 0, tmpClientPublicKey, true)
  198. if errorBool {
  199. continue
  200. }
  201. getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, leaderWorkerConnection)
  202. m.Lock()
  203. clientData[*clientPublicKey] = clientKeys
  204. m.Unlock()
  205. //gets dpfQuery from leader
  206. dpfLengthBytes, errorBool := readFromWError(leaderWorkerConnection, 4)
  207. if errorBool {
  208. continue
  209. }
  210. dpfLength := byteToInt(dpfLengthBytes)
  211. dpfQueryBEncrypted, errorBool := readFromWError(leaderWorkerConnection, dpfLength)
  212. if errorBool {
  213. continue
  214. }
  215. //decrypt dpfQueryB for sorting into db
  216. var decryptNonce [24]byte
  217. copy(decryptNonce[:], dpfQueryBEncrypted[:24])
  218. dpfQueryB, ok := box.Open(nil, dpfQueryBEncrypted[24:], &decryptNonce, clientPublicKey, followerPrivateKey)
  219. if !ok {
  220. panic("dpfQueryB decryption not ok")
  221. }
  222. ds := int(C.db[0].dataSize)
  223. dataShareFollower := make([]byte, ds)
  224. pos := C.getUint128_t(C.int(virtualAddresses[dbWriteSize]))
  225. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryB[0]), pos, C.int(ds), (*C.uchar)(&dataShareFollower[0]))
  226. writeTo(leaderWorkerConnection, dataShareFollower)
  227. dataShareLeader, errorBool := readFromWError(leaderWorkerConnection, ds)
  228. if errorBool {
  229. continue
  230. }
  231. auditXOR := make([]byte, ds)
  232. passedAudit := true
  233. for i := 0; i < ds; i++ {
  234. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  235. //client tried to write to a position that is not a virtuallAddress
  236. if auditXOR[i] != 0 {
  237. passedAudit = false
  238. }
  239. }
  240. if passedAudit {
  241. //run dpf, xor into local db
  242. for i := 0; i < dbSize; i++ {
  243. ds := int(C.db[i].dataSize)
  244. dataShare := make([]byte, ds)
  245. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  246. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryB[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  247. for j := 0; j < ds; j++ {
  248. db[i][j] = db[i][j] ^ dataShare[j]
  249. }
  250. }
  251. //xor the worker's DB into the main DB
  252. for i := 0; i < dbSize; i++ {
  253. m.Lock()
  254. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  255. m.Unlock()
  256. }
  257. }
  258. }
  259. }
  260. func phase2(leaderWorkerConnection net.Conn) {
  261. //gets current seed
  262. seedFollower := make([]byte, 16)
  263. C.readSeed((*C.uchar)(&seedFollower[0]))
  264. //get data
  265. dbSize := int(C.dbSize)
  266. tmpdbFollower := make([][]byte, dbSize)
  267. for i := range tmpdbFollower {
  268. tmpdbFollower[i] = make([]byte, dataLength)
  269. }
  270. for i := 0; i < dbSize; i++ {
  271. C.readData(C.int(i), (*C.uchar)(&tmpdbFollower[i][0]))
  272. }
  273. //receive seed from leader
  274. seedLeader := readFrom(leaderWorkerConnection, 16)
  275. //receive data from leader
  276. tmpdbLeader := make([][]byte, dbSize)
  277. for i := range tmpdbLeader {
  278. tmpdbLeader[i] = make([]byte, dataLength)
  279. }
  280. for i := 0; i < dbSize; i++ {
  281. tmpdbLeader[i] = readFrom(leaderWorkerConnection, dataLength)
  282. }
  283. //writes seed to leader
  284. writeTo(leaderWorkerConnection, seedFollower)
  285. //write data to leader
  286. for i := 0; i < dbSize; i++ {
  287. writeTo(leaderWorkerConnection, tmpdbFollower[i])
  288. }
  289. //put together the db
  290. tmpdb := make([][]byte, dbSize)
  291. for i := range tmpdb {
  292. tmpdb[i] = make([]byte, dataLength)
  293. }
  294. //get own Ciphers
  295. ciphersFollowers := make([]*C.uchar, dbSize)
  296. for i := 0; i < dbSize; i++ {
  297. ciphersFollowers[i] = (*C.uchar)(C.malloc(16))
  298. }
  299. for i := 0; i < dbSize; i++ {
  300. C.getCipher(0, C.int(i), ciphersFollowers[i])
  301. }
  302. //receive ciphers from leader
  303. ciphersLeader := make([]byte, dbSize*16)
  304. for i := 0; i < dbSize; i++ {
  305. _, err := leaderWorkerConnection.Read(ciphersLeader[i*16:])
  306. if err != nil {
  307. panic(err)
  308. }
  309. }
  310. //send own Ciphers to leader
  311. for i := 0; i < dbSize; i++ {
  312. writeTo(leaderWorkerConnection, C.GoBytes(unsafe.Pointer(ciphersFollowers[i]), 16))
  313. }
  314. //put in ciphers from leader
  315. for i := 0; i < dbSize; i++ {
  316. C.putCipher(0, C.int(i), (*C.uchar)(&ciphersLeader[i*16]))
  317. }
  318. for i := 0; i < dbSize; i++ {
  319. 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]))
  320. }
  321. var tweets []lib.Tweet
  322. for i := 0; i < dbSize; i++ {
  323. //discard cover message
  324. if tmpdb[i][0] == 0 {
  325. continue
  326. } else if -1 == strings.Index(string(tmpdb[i]), ";;") {
  327. continue
  328. } else {
  329. //reconstruct tweet
  330. var position int = 0
  331. var topics []string
  332. var topic string
  333. var text string
  334. for _, letter := range tmpdb[i] {
  335. if string(letter) == ";" {
  336. if topic != "" {
  337. topics = append(topics, topic)
  338. topic = ""
  339. }
  340. position++
  341. } else {
  342. if position == 0 {
  343. if string(letter) == "," {
  344. topics = append(topics, topic)
  345. topic = ""
  346. } else {
  347. //change this works for ints, need to be changed for strings
  348. topic = topic + fmt.Sprint((int(letter)))
  349. }
  350. } else if position == 1 {
  351. text = text + string(letter)
  352. }
  353. }
  354. }
  355. tweet := lib.Tweet{"", -1, topics, text, round}
  356. tweets = append(tweets, tweet)
  357. }
  358. }
  359. //fmt.Println("tweets recovered: ", tweets)
  360. //sort into read db
  361. lib.NewEntries(tweets, 0)
  362. //reset write db after the tweets were moved to read db
  363. C.resetDb()
  364. //gets current dbWriteSize from leader
  365. dbWriteSizeBytes := readFrom(leaderWorkerConnection, 4)
  366. dbWriteSize = byteToInt(dbWriteSizeBytes)
  367. }
  368. func addTestTweets() {
  369. //creates test tweets
  370. tweets := make([]lib.Tweet, 5)
  371. for i := range tweets {
  372. j := i
  373. if i == 1 {
  374. j = 0
  375. }
  376. text := "Text " + strconv.Itoa(i)
  377. var topics []string
  378. topics = append(topics, "Topic "+strconv.Itoa(j))
  379. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  380. }
  381. lib.NewEntries(tweets, 0)
  382. }
  383. func phase3(leaderWorkerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex) {
  384. for {
  385. gotClient, errorBool := readFromWError(leaderWorkerConnection, 1)
  386. if errorBool {
  387. continue
  388. }
  389. //this worker is done
  390. if gotClient[0] == 0 {
  391. wg.Done()
  392. return
  393. }
  394. subPhase, errorBool := readFromWError(leaderWorkerConnection, 1)
  395. if errorBool {
  396. continue
  397. }
  398. var clientPublicKey [32]byte
  399. _, err := leaderWorkerConnection.Read(clientPublicKey[:])
  400. if err != nil {
  401. fmt.Println("no error handling")
  402. panic(err)
  403. }
  404. //gets the client data
  405. m.RLock()
  406. clientKeys := clientData[clientPublicKey]
  407. m.RUnlock()
  408. if subPhase[0] == 0 || subPhase[0] == 1 {
  409. clientKeys, _, errorBool = handlePirQuery(clientKeys, leaderWorkerConnection, int(subPhase[0]), clientPublicKey, false)
  410. if errorBool {
  411. continue
  412. }
  413. }
  414. getSendTweets(clientKeys, nil, leaderWorkerConnection)
  415. wantsArchive, errorBool := readFromWError(leaderWorkerConnection, 1)
  416. if errorBool {
  417. continue
  418. }
  419. if wantsArchive[0] == 1 {
  420. _, archiveQuerys, errorBool := handlePirQuery(clientKeys, leaderWorkerConnection, -1, clientPublicKey, false)
  421. if errorBool {
  422. continue
  423. }
  424. getSendTweets(clientKeys, archiveQuerys, leaderWorkerConnection)
  425. }
  426. //saves clientKeys
  427. m.Lock()
  428. clientData[clientPublicKey] = clientKeys
  429. m.Unlock()
  430. }
  431. }
  432. //gets tweet from db and sends them to leader
  433. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, leaderWorkerConnection net.Conn) {
  434. tmpNeededSubscriptions := neededSubscriptions
  435. if archiveQuerys != nil {
  436. tmpNeededSubscriptions = len(archiveQuerys)
  437. }
  438. for i := 0; i < tmpNeededSubscriptions; i++ {
  439. //gets all requested tweets
  440. var tweets []byte
  441. if archiveQuerys == nil {
  442. tweets = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0)
  443. } else {
  444. tweets = lib.GetTweets(archiveQuerys[i], dataLength, 1)
  445. }
  446. //expand sharedSecret so it is of right length
  447. expandBy := len(tweets) / 32
  448. var expandedSharedSecret []byte
  449. for i := 0; i < expandBy; i++ {
  450. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  451. }
  452. //Xor's sharedSecret with all tweets
  453. lib.Xor(expandedSharedSecret[:], tweets)
  454. lib.Xor(tweets, expandedSharedSecret[:])
  455. //sends tweets to leader
  456. tweetsLengthBytes := intToByte(len(tweets))
  457. writeTo(leaderWorkerConnection, tweetsLengthBytes)
  458. writeTo(leaderWorkerConnection, tweets)
  459. }
  460. }
  461. //returns true if client connection is lost
  462. func handlePirQuery(clientKeys clientKeys, leaderWorkerConnection net.Conn, subPhase int, clientPublicKey [32]byte, doAuditing bool) (clientKeys, [][]byte, bool) {
  463. archiveNeededSubscriptions := make([]byte, 4)
  464. if subPhase == -1 {
  465. archiveNeededSubscriptions, errorBool := readFromWError(leaderWorkerConnection, 4)
  466. if errorBool {
  467. return clientKeys, nil, true
  468. }
  469. ignoreMe = archiveNeededSubscriptions
  470. }
  471. //gets the msg length
  472. msgLengthBytes, errorBool := readFromWError(leaderWorkerConnection, 4)
  473. if errorBool {
  474. return clientKeys, nil, true
  475. }
  476. msgLength := byteToInt(msgLengthBytes)
  477. //gets the message
  478. message, errorBool := readFromWError(leaderWorkerConnection, msgLength)
  479. if errorBool {
  480. return clientKeys, nil, true
  481. }
  482. var decryptNonce [24]byte
  483. copy(decryptNonce[:], message[:24])
  484. decrypted, ok := box.Open(nil, message[24:], &decryptNonce, &clientPublicKey, followerPrivateKey)
  485. if !ok {
  486. fmt.Println("pirQuery decryption not ok")
  487. return clientKeys, nil, true
  488. }
  489. //gets sharedSecret
  490. if subPhase == 0 {
  491. var newSharedSecret [32]byte
  492. for index := 0; index < 32; index++ {
  493. newSharedSecret[index] = decrypted[index]
  494. }
  495. clientKeys.SharedSecret = newSharedSecret
  496. decrypted = decrypted[32:]
  497. if doAuditing {
  498. result := make([][]byte, 1)
  499. result[0] = decrypted
  500. return clientKeys, result, false
  501. }
  502. //follower updates sharedSecret
  503. } else if subPhase == 1 {
  504. sharedSecret := clientKeys.SharedSecret
  505. sharedSecret = sha256.Sum256(sharedSecret[:])
  506. clientKeys.SharedSecret = sharedSecret
  507. }
  508. //follower expects pirQuery
  509. //transforms byteArray to ints of wanted topics
  510. tmpNeededSubscriptions := neededSubscriptions
  511. tmpTopicAmount := topicAmount
  512. if subPhase == -1 {
  513. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  514. _, tmpTopicAmount = lib.GetTopicList(1)
  515. }
  516. pirQueryFlattened := decrypted
  517. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  518. for i := range pirQuerys {
  519. pirQuerys[i] = make([]byte, tmpTopicAmount)
  520. }
  521. for i := 0; i < tmpNeededSubscriptions; i++ {
  522. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  523. }
  524. //sets the pirQuery for the client in case whe are not archiving
  525. if subPhase != -1 {
  526. clientKeys.PirQuery = pirQuerys
  527. }
  528. return clientKeys, pirQuerys, false
  529. }
  530. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, leaderWorkerConnection net.Conn) {
  531. //xores all requested addresses into virtuallAddress
  532. virtualAddress := make([]byte, 4)
  533. for index, num := range pirQuery {
  534. if num == 1 {
  535. currentAddress := intToByte(virtualAddresses[index])
  536. for i := 0; i < 4; i++ {
  537. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  538. }
  539. }
  540. }
  541. //xores the sharedSecret
  542. for i := 0; i < 4; i++ {
  543. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  544. }
  545. writeTo(leaderWorkerConnection, virtualAddress)
  546. }
  547. //sends the array to the connection
  548. func writeTo(connection net.Conn, array []byte) {
  549. _, err := connection.Write(array)
  550. if err != nil {
  551. panic(err)
  552. }
  553. }
  554. //reads an array which is returned and of size "size" from the connection
  555. //returned bool is one if connection to client was lost
  556. func readFrom(connection net.Conn, size int) []byte {
  557. array := make([]byte, size)
  558. _, err := connection.Read(array)
  559. if err != nil {
  560. panic(err)
  561. }
  562. return array
  563. }
  564. //reads an array which is returned and of size "size" from the connection
  565. //returns true if connection to client is lost
  566. func readFromWError(connection net.Conn, size int) ([]byte, bool) {
  567. array := make([]byte, size+1)
  568. _, err := connection.Read(array)
  569. if err != nil {
  570. panic(err)
  571. }
  572. if array[0] == 1 {
  573. return nil, true
  574. }
  575. return array[1:], false
  576. }
  577. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  578. var topics []string
  579. var topic string
  580. var position int = 0
  581. for _, letter := range topicsAsBytes {
  582. if string(letter) == "," {
  583. topics[position] = topic
  584. topic = ""
  585. position++
  586. } else {
  587. topic = topic + string(letter)
  588. }
  589. }
  590. return topics
  591. }
  592. func byteToInt(myBytes []byte) (x int) {
  593. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  594. return
  595. }
  596. func intToByte(myInt int) (retBytes []byte) {
  597. retBytes = make([]byte, 4)
  598. retBytes[3] = byte((myInt >> 24) & 0xff)
  599. retBytes[2] = byte((myInt >> 16) & 0xff)
  600. retBytes[1] = byte((myInt >> 8) & 0xff)
  601. retBytes[0] = byte(myInt & 0xff)
  602. return
  603. }