aboutsummaryrefslogtreecommitdiff
path: root/gittorrentd
blob: 0ac810d9d2893b147236fb84a15d4c6bda23ea29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env node

var DHT = require('bittorrent-dht')
var EC = require('elliptic').ec
var ed25519 = new EC('ed25519')
var exec = require('child_process').exec
var glob = require('glob')
var fs = require('fs')
var hat = require('hat')
var net = require('net')
var Protocol = require('bittorrent-protocol')
var spawn = require('child_process').spawn
var ut_gittorrent = require('ut_gittorrent')
var ut_metadata = require('ut_metadata')
var WebTorrent = require('webtorrent')
var zeroFill = require('zero-fill')
var config = require('./config')

// BitTorrent client version string (used in peer ID).
// Generated from package.json major and minor version. For example:
//   '0.16.1' -> '0016'
//   '1.2.5' -> '0102'
//
var VERSION = require('./package.json').version
  .match(/([0-9]+)/g).slice(0, 2).map(zeroFill(2)).join('')

function die (error) {
  console.error(error)
  process.exit(1)
}

var dht = new DHT({
  bootstrap: config.dht.bootstrap
})
dht.listen(config.dht.listen)

var announcedRefs = {
}
var userProfile = {
  repositories: {}
}

var key = create_or_read_keyfile()

function create_or_read_keyfile () {
  if (!fs.existsSync(config.key)) {
    var keypair = new EC('ed25519').genKeyPair()
    fs.writeFileSync(config.key, JSON.stringify({
      pub: keypair.getPublic('hex'),
      priv: keypair.getPrivate('hex')
    }))
  }

  // Okay, now the file exists, whether created here or not.
  var key = JSON.parse(fs.readFileSync(config.key).toString())
  return ed25519.keyPair({
    priv: key.priv,
    privEnc: 'hex',
    pub: key.pub,
    pubEnc: 'hex'
  })
}

function bpad (n, buf) {
  if (buf.length === n) return buf
  if (buf.length < n) {
    var b = new Buffer(n)
    buf.copy(b, n - buf.length)
    for (var i = 0; i < n - buf.length; i++) b[i] = 0
    return b
  }
}

dht.on('ready', function () {
  // Spider all */.git dirs and announce all refs.
  var repos = glob.sync('*/{,.git/}git-daemon-export-ok', {strict: false})
  var count = repos.length
  repos.forEach(function (repo) {
    console.log('in repo ' + repo)
    repo = repo.replace(/git-daemon-export-ok$/, '')
    console.log(repo)

    var reponame = repo.replace(/\/.git\/$/, '')
    userProfile.repositories[reponame] = {}

    var upload = spawn('git-upload-pack', ['--strict', repo])
    upload.stdout.on('data', function (line) {
      var lines = line.toString().split('\n')
      lines.forEach(function (line) {
        var arr = line.toString().split(' ')
        if (arr.length < 2) {
          return
        }
        var sha = arr[0].toString()
        // First four chars are git-upload-pack's length-of-line metadata.
        sha = sha.substring(4)
        if (arr.length == 2) {
          var ref = arr[1].toString()
          var branch = ref.match(/^refs\/heads\/(.*)/)
          // FIXME: Can't pull in too many branches.
          // if (!branch) {
          //   branch = ref.match(/^refs\/remotes\/(.*)/)
          // }
          if (branch) {
            userProfile.repositories[reponame][ref] = sha
          }
          if (branch && !announcedRefs[sha]) {
            branch = branch[1]
            console.log('Announcing ' + sha + ' for ' + branch + ' on repo ' + repo)
            announcedRefs[sha] = repo
            dht.announce(sha, config.dht.announce, function (err) {
              if (err !== null) {
                console.log('Announced ' + sha)
              }
            })
          }
        } else if (arr.length > 2 && arr[1].search(/^HEAD/) !== -1) {
          // Probably the first line; line[0] has the hash, line[1] has HEAD,
          // and beyond are the supported features.
          userProfile.repositories[reponame]['HEAD'] = sha
        }
      })
      // Callback counting for repos
      count--
      if (count <= 0) {
        publish_mutable_key()
      }
    })
    upload.stdout.on('end', function () {
      console.log('end')
    })
    upload.on('exit', function (code) {
      if (code !== 0) {
        die('Failed: ' + code)
      }
    })
  })

  function publish_mutable_key () {
    var json = JSON.stringify(userProfile)
    if (json.length > 950) {
      console.error("Can't publish mutable key: doesn't fit in 950 bytes.")
      return false
    }
    var value = new Buffer(json.length)
    value.write(json)
    var sig = key.sign(value)
    var opts = {
      k: bpad(32, Buffer(key.getPublic().x.toArray())),
      seq: 0,
      v: value,
      sig: Buffer.concat([
        bpad(32, Buffer(sig.r.toArray())),
        bpad(32, Buffer(sig.s.toArray()))
    ])}
    console.log(json)
    dht.put(opts, function (errors, hash) {
      console.error('errors=', errors)
      console.log('hash=', hash.toString('hex'))
    })
  }

  net.createServer(function (socket) {
    var wire = new Protocol()
    wire.use(ut_gittorrent())
    wire.use(ut_metadata())
    socket.pipe(wire).pipe(socket)
    wire.on('handshake', function (infoHash, peerId) {
      console.log('Received handshake for ' + infoHash.toString('hex'))
      var myPeerId = new Buffer('-WW' + VERSION + '-' + hat(48), 'utf8')
      wire.handshake(new Buffer(infoHash), new Buffer(myPeerId))
    })
    wire.ut_gittorrent.on('generatePack', function (sha) {
      console.error('calling git pack-objects')
      var filename = sha + '.pack'
      var stream = fs.createWriteStream(filename)
      if (!announcedRefs[sha]) {
        console.error('Asked for an unknown sha: ' + sha)
        return
      }
      var directory = announcedRefs[sha]
      var pack = spawn('git', ['pack-objects', '--revs', '--thin', '--stdout', '--delta-base-offset'], {cwd: directory})
      pack.on('close', function (code) {
        if (code !== 0) {
          console.error('git pack-objects process exited with code ' + code)
        } else {
          console.error('Finished writing ' + filename)
          var webtorrent = new WebTorrent({
            dht: {bootstrap: config.dht.bootstrap},
            tracker: false
          })
          webtorrent.seed(filename, function onTorrent (torrent) {
            console.error(torrent.infoHash)
            wire.ut_gittorrent.sendTorrent(torrent.infoHash)
          })
        }
      })
      pack.stdout.pipe(stream)
      pack.stderr.on('data', function (data) {
        console.error(data.toString())
      })
      pack.on('exit', function () {
        console.log('exited')
      })
      pack.stdin.write(sha + '\n')
      pack.stdin.write('--not\n\n')
    })
  }).listen(config.dht.announce)
})