Class: MPW::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/mpw/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeServer

Constructor



17
18
19
# File 'lib/mpw/server.rb', line 17

def initialize
  YAML::ENGINE.yamler='syck'
end

Instance Attribute Details

#error_msgObject

Returns the value of attribute error_msg.



14
15
16
# File 'lib/mpw/server.rb', line 14

def error_msg
  @error_msg
end

Instance Method Details

#checkconfig(file_config) ⇒ Object

Check the config file @args: file_config -> the configuration file @rtrn: true if the config file is correct



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/mpw/server.rb', line 258

def checkconfig(file_config)
  config    = YAML::load_file(file_config)
  @host     = config['config']['host']
  @port     = config['config']['port'].to_i
  @data_dir = config['config']['data_dir']
  @log_file = config['config']['log_file']
  @timeout  = config['config']['timeout'].to_i

  if @host.empty? or @port <= 0 or @data_dir.empty? 
    puts I18n.t('checkconfig.fail')
    puts I18n.t('checkconfig.empty')
    return false
  end

  if not Dir.exist?(@data_dir)
    puts I18n.t('checkconfig.fail')
    puts I18n.t('checkconfig.datadir')
    return false
  end

  if @log_file.nil? or @log_file.empty?
    puts I18n.t('checkconfig.fail')
    puts I18n.t('checkconfig.log_file_empty')
    return false
  else
    begin
      @log = Logger.new(@log_file)
    rescue
      puts I18n.t('checkconfig.fail')
      puts I18n.t('checkconfig.log_file_create')
      return false
    end
  end

  return true
rescue Exception => e 
  puts "#{I18n.t('checkconfig.fail')}\n#{e}"
  return false
end

#close_connection(client) ⇒ Object

Close the client connection @args: client -> client connection



250
251
252
253
# File 'lib/mpw/server.rb', line 250

def close_connection(client)
    client.puts "Closing the connection. Bye!"
    client.close
end

#delete_file(msg) ⇒ Object

Remove a gpg file @args: msg -> message puts by the client @rtrn: json message



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
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/mpw/server.rb', line 178

def delete_file(msg)
  gpg_key = msg['gpg_key'].sub('@', '_')

  if msg['suffix'].nil? or msg['suffix'].empty?
    file_gpg = "#{@data_dir}/#{gpg_key}.yml"
  else
    file_gpg = "#{@data_dir}/#{gpg_key}-#{msg['suffix']}.yml"
  end

  if not File.exist?(file_gpg)
    send_msg = {:action  => 'delete',
                :gpg_key => msg['gpg_key'],
                :error   => nil
               }

    return send_msg.to_json
  end

  gpg_data = YAML::load_file(file_gpg)
  salt     = gpg_data['gpg']['salt']
  hash     = gpg_data['gpg']['hash']

  if is_authorized?(msg['password'], salt, hash)
    begin
      File.unlink(file_gpg)

      send_msg = {action:  'delete',
                  gpg_key: msg['gpg_key'],
                  error:   nil
                 }
    rescue Exception => e
      send_msg = {action:  'delete',
                  gpg_key: msg['gpg_key'],
                  error:   'server.error.client.unknown'
                 }
    end
  else
    send_msg = {action:  'delete',
                gpg_key: msg['gpg_key'],
                error:   'server.error.client.no_authorized'
               }
  end
  
  return send_msg.to_json
end

#generate_salt(length = 4) ⇒ Object

Generate a random salt @args: length -> the length salt @rtrn: a random string



331
332
333
334
335
336
337
338
339
# File 'lib/mpw/server.rb', line 331

def generate_salt(length=4)
  if length.to_i <= 0 or length.to_i > 16
    length = 4
  else
    length = length.to_i
  end

  return ([*('A'..'Z'),*('a'..'z'),*('0'..'9')]).sample(length).join
end

#get_client_msg(client) ⇒ Object

Get message to client @args: client -> client connection @rtrn: array of the json string, or false if isn’t json message



240
241
242
243
244
245
246
# File 'lib/mpw/server.rb', line 240

def get_client_msg(client)
  msg = client.gets
  return JSON.parse(msg)
rescue
  closeConnection(client)
  return false
end

#get_file(msg) ⇒ Object

Get a gpg file @args: msg -> message puts by the client @rtrn: json message



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
# File 'lib/mpw/server.rb', line 73

def get_file(msg)
  gpg_key = msg['gpg_key'].sub('@', '_')

  if msg['suffix'].nil? or msg['suffix'].empty?
    file_gpg = "#{@data_dir}/#{gpg_key}.yml"
  else
    file_gpg = "#{@data_dir}/#{gpg_key}-#{msg['suffix']}.yml"
  end

  if File.exist?(file_gpg)
    gpg_data    = YAML::load_file(file_gpg)
    salt        = gpg_data['gpg']['salt']
    hash        = gpg_data['gpg']['hash']
    data        = gpg_data['gpg']['data']

    if is_authorized?(msg['password'], salt, hash)
      send_msg = {action:  'get',
                  gpg_key: msg['gpg_key'],
                  data:    data,
                  error:   nil
                 }
    else
      send_msg = {action:  'get',
                  gpg_key: msg['gpg_key'],
                  error:   'server.error.client.no_authorized'
                 }
    end
  else
    send_msg = {action:  'get',
                gpg_key: msg['gpg_key'],
                data:    '',
                error:   nil
               }
  end

  return send_msg.to_json
end

#is_authorized?(password, salt, hash) ⇒ Boolean

Check is the hash equal the password with the salt @args: password -> the user password

salt -> the salt
hash -> the hash of the password with the salt

@rtrn: true is is good, else false

Returns:

  • (Boolean)


229
230
231
232
233
234
235
# File 'lib/mpw/server.rb', line 229

def is_authorized?(password, salt, hash)
  if hash == Digest::SHA256.hexdigest(salt + password)
    return true
  else
    return false
  end
end

#setup(file_config) ⇒ Object

Create a new config file @args: file_config -> the configuration file @rtrn: true if le config file is create



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/mpw/server.rb', line 301

def setup(file_config)
  puts I18n.t('form.setup.title')
  puts '--------------------'
  host     = ask(I18n.t('form.setup.host')).to_s
  port     = ask(I18n.t('form.setup.port')).to_s
  data_dir = ask(I18n.t('form.setup.data_dir')).to_s
  log_file = ask(I18n.t('form.setup.log_file')).to_s
  timeout  = ask(I18n.t('form.setup.timeout')).to_s

  config = {'config' => {'host'     => host,
                         'port'     => port,
                         'data_dir' => data_dir,
                         'log_file' => log_file,
                         'timeout'  => timeout
                        }
           }

  File.open(file_config, 'w') do |file|
    file << config.to_yaml
  end
    
  return true
rescue Exception => e 
  puts "#{I18n.t('form.setup.not_valid')}\n#{e}"
  return false
end

#startObject

Start the server



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
# File 'lib/mpw/server.rb', line 22

def start
  server = TCPServer.open(@host, @port)
  @log.info("The server is started on #{@host}:#{@port}")

  loop do
    Thread.start(server.accept) do |client|
      @log.info("#{client.peeraddr[3]} is connected")

      while true do
        msg = get_client_msg(client)

        next if not msg
        
        if msg['gpg_key'].nil? or msg['gpg_key'].empty? or msg['password'].nil? or msg['password'].empty?
          @log.warning("#{client.peeraddr[3]} is disconnected because no password or no gpg_key")
          close_connection(client)
          next
        end

        case msg['action']
        when 'get'
          @log.debug("#{client.peeraddr[3]} GET gpg_key=#{msg['gpg_key']} suffix=#{msg['suffix']}")
          client.puts get_file(msg)
        when 'update'
          @log.debug("#{client.peeraddr[3]} UPDATE gpg_key=#{msg['gpg_key']} suffix=#{msg['suffix']}")
          client.puts update_file(msg)
        when 'delete'
          @log.debug("#{client.peeraddr[3]} DELETE gpg_key=#{msg['gpg_key']} suffix=#{msg['suffix']}")
          client.puts delete_file(msg)
        else
          @log.warning("#{client.peeraddr[3]} is disconnected because unkwnow command")
          send_msg = {action: 'unknown',
                      gpg_key: msg['gpg_key'],
                      error:  'server.error.client.unknown'
                     }
          client.puts send_msg 
          close_connection(client)
        end
      end
    end
  end

rescue Exception => e
  puts "Impossible to start the server: #{e}"
  @log.error("Impossible to start the server: #{e}")
  exit 2
end

#update_file(msg) ⇒ Object

Update a file @args: msg -> message puts by the client @rtrn: json message



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
# File 'lib/mpw/server.rb', line 114

def update_file(msg)
  gpg_key = msg['gpg_key'].sub('@', '_')
  data    = msg['data']

  if data.nil? or data.empty?
    send_msg = {action:  'update',
                gpg_key: msg['gpg_key'],
                error:   'server.error.client.no_data'
               }
    
    return send_msg.to_json
  end

  if msg['suffix'].nil? or msg['suffix'].empty?
    file_gpg = "#{@data_dir}/#{gpg_key}.yml"
  else
    file_gpg = "#{@data_dir}/#{gpg_key}-#{msg['suffix']}.yml"
  end

  if File.exist?(file_gpg)
    gpg_data  = YAML::load_file(file_gpg)
    salt      = gpg_data['gpg']['salt']
    hash      = gpg_data['gpg']['hash']

  else
    salt = generate_salt
    hash = Digest::SHA256.hexdigest(salt + msg['password'])
  end

  if is_authorized?(msg['password'], salt, hash)
    begin
      config = {'gpg' => {'salt' => salt,
                          'hash' => hash,
                          'data' => data
                         }
               }

      File.open(file_gpg, 'w+') do |file|
        file << config.to_yaml
      end

      send_msg = {action:  'update',
                  gpg_key: msg['gpg_key'],
                  error:   nil
                 }
    rescue Exception => e
      send_msg = {action:  'update',
                  gpg_key: msg['gpg_key'],
                  error:   'server.error.client.unknown'
                 }
    end
  else
    send_msg = {action:  'update',
                gpg_key: msg['gpg_key'],
                error:   'server.error.client.no_authorized'
               }
  end
  
  return send_msg.to_json
end