Class: Sambal::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/sambal/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(user_options = {}) ⇒ Client

Returns a new instance of Client


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
# File 'lib/sambal/client.rb', line 29

def initialize(user_options={})
  begin
    options = parsed_options(user_options)
    @timeout = options[:timeout].to_i

    password =
      if options[:authfile]
        "--authentication-file #{options[:authfile]}"
      elsif options[:password]
        options[:password]
      else
        '--no-pass'
      end
    command = "COLUMNS=#{options[:columns]} smbclient \"//#{options[:host]}/#{options[:share]}\" #{password}"

    @output, @input, @pid = PTY.spawn("#{command} #{option_flags(options)}")

    res = @output.expect(/(.*\n)?smb:.*\\>/, @timeout)[0] rescue nil
    @connected = case res
    when nil
      false
    when /^put/
      res['putting'].nil? ? false : true
    else
      if res['NT_STATUS']
        false
      elsif res['timed out'] || res['Server stopped']
        false
      else
        true
      end
    end

    unless @connected
      close if @pid
      raise 'Failed to connect'
    end
  rescue => e
    raise RuntimeError, "Unknown Process Failed!! (#{$!.to_s}): #{e.message.inspect}\n"+e.backtrace.join("\n")
  end
end

Instance Attribute Details

#connectedObject (readonly)

Returns the value of attribute connected


10
11
12
# File 'lib/sambal/client.rb', line 10

def connected
  @connected
end

Instance Method Details

#ask(cmd) ⇒ Object


254
255
256
257
258
259
260
261
262
263
# File 'lib/sambal/client.rb', line 254

def ask(cmd)
  @input.print("#{cmd}\n")
  response = @output.expect(/^smb:.*\\>/,@timeout)[0] rescue nil
  if response.nil?
    $stderr.puts "Failed to do #{cmd}"
    raise "Failed to do #{cmd}"
  else
    response
  end
end

#ask_wrapped(cmd, filenames) ⇒ Object


265
266
267
# File 'lib/sambal/client.rb', line 265

def ask_wrapped(cmd,filenames)
  ask wrap_filenames(cmd,filenames)
end

#cd(dir) ⇒ Object


105
106
107
108
109
110
111
112
# File 'lib/sambal/client.rb', line 105

def cd(dir)
  response = ask("cd \"#{dir}\"")
  if response.split("\r\n").join('') =~ /NT_STATUS_OBJECT_NAME_NOT_FOUND/
    Response.new(response, false)
  else
    Response.new(response, true)
  end
end

#closeObject


247
248
249
250
251
252
# File 'lib/sambal/client.rb', line 247

def close
  @input.close
  @output.close
  Process.wait(@pid)
  @connected = false
end

#del(filename) ⇒ Object


203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/sambal/client.rb', line 203

def del(filename)
  begin
    file_context(filename) do |file|
      response = ask_wrapped 'del', file
      next_line = response.split("\n")[1]
      if next_line =~ /^smb:.*\\>/
      Response.new(response, true)
      #elsif next_line =~ /^NT_STATUS_NO_SUCH_FILE.*$/
      #  Response.new(response, false)
      #elsif next_line =~ /^NT_STATUS_ACCESS_DENIED.*$/
      #  Response.new(response, false)
      else
        Response.new(response, false)
      end
    end
  rescue InternalError => e
    Response.new(e.message, false)
  end
  #end
  #if (path_parts = file.split('/')).length>1
  #  file = path_parts.pop
  #  subdirs = path_parts.length
  #  dir = path_parts.join('/')
  #  cd dir
  #end
#  response = ask "del #{file}"
#  next_line = response.split("\n")[1]
#  if next_line =~ /^smb:.*\\>/
#    Response.new(response, true)
#  #elsif next_line =~ /^NT_STATUS_NO_SUCH_FILE.*$/
#  #  Response.new(response, false)
#  #elsif next_line =~ /^NT_STATUS_ACCESS_DENIED.*$/
#  #  Response.new(response, false)
#  else
#    Response.new(response, false)
#  end
#rescue InternalError => e
#  Response.new(e.message, false)
#ensure
#  unless subdirs.nil?
#    subdirs.times { cd '..' }
#  end
end

#exists?(path) ⇒ Boolean

Returns:

  • (Boolean)

101
102
103
# File 'lib/sambal/client.rb', line 101

def exists?(path)
  ls(path).key? File.basename(path)
end

#file_context(path) ⇒ Object


79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/sambal/client.rb', line 79

def file_context(path)
  if (path_parts = path.split('/')).length>1
    file = path_parts.pop
    subdirs = path_parts.length
    dir = path_parts.join('/')
    cd dir
  else
    file = path
  end
  begin
    yield(file)
  ensure
    unless subdirs.nil?
      subdirs.times { cd '..' }
    end
  end
end

#get(filename, output) ⇒ Object


114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/sambal/client.rb', line 114

def get(filename, output)
  begin
    file_context(filename) do |file|
      response = ask_wrapped 'get', [file, output]
      if response =~ /^getting\sfile.*$/
        Response.new(response, true)
      else
        Response.new(response, false)
      end
    end
  rescue InternalError => e
    Response.new(e.message, false)
  end
end

#loggerObject


71
72
73
# File 'lib/sambal/client.rb', line 71

def logger
  @logger ||= Logger.new(STDOUT)
end

#logger=(l) ⇒ Object


75
76
77
# File 'lib/sambal/client.rb', line 75

def logger=(l)
  @logger = l
end

#ls(qualifier = '*') ⇒ Object


97
98
99
# File 'lib/sambal/client.rb', line 97

def ls(qualifier = '*')
  parse_files(ask_wrapped('ls', qualifier))
end

#mkdir(directory) ⇒ Object


168
169
170
171
172
173
174
175
176
# File 'lib/sambal/client.rb', line 168

def mkdir(directory)
  return Response.new('directory name is empty', false) if directory.strip.empty?
  response = ask_wrapped('mkdir', directory)
  if response =~ /NT_STATUS_OBJECT_NAME_(INVALID|COLLISION)/
    Response.new(response, false)
  else
    Response.new(response, true)
  end
end

#parse_files(str) ⇒ Object

Parse output from Client#ls Returns Hash of file names with meta information


277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/sambal/client.rb', line 277

def parse_files(str)
  listing = str.each_line.inject({}) do |files, line|
    line.strip!
    name = line[/.*(?=\b\s+[ABDHNRS]+\s+\d+)/]
    name ||= line[/^\.\.|^\./]

    if name
      line.sub!(name, '')
      line.strip!

      type = line[0] == "D" ? :directory : :file
      size = line[/\d+/]

      date = line[/(?<=\d  )\D.*$/]
      modified = (Time.parse(date) rescue "!!#{date}")

      files[name] = {
        type: type,
        size: size,
        modified: modified
      }
    end
    files
  end
  Hash[listing.sort]
end

#parsed_options(user_options) ⇒ Object


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/sambal/client.rb', line 12

def parsed_options(user_options)
  default_options = {
    domain: 'WORKGROUP',
    host: '127.0.0.1',
    share: '',
    user: 'guest',
    password: false,
    port: 445,
    timeout: 10,
    columns: 80
  }

  options = default_options.merge(user_options)
  options[:ip_address] ||= options[:host] if options[:host] == default_options[:host]
  options
end

#put(file, destination) ⇒ Object


140
141
142
143
144
145
146
147
148
149
# File 'lib/sambal/client.rb', line 140

def put(file, destination)
  response = ask_wrapped 'put', [file, destination]
  if response =~ /^putting\sfile.*$/
    Response.new(response, true)
  else
    Response.new(response, false)
  end
rescue InternalError => e
  Response.new(e.message, false)
end

#put_content(content, destination) ⇒ Object


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/sambal/client.rb', line 151

def put_content(content, destination)
  t = Tempfile.new("upload-smb-content-#{destination}")
  File.open(t.path, 'w') do |f|
    f << content
  end
  response = ask_wrapped 'put', [t.path, destination]
  if response =~ /^putting\sfile.*$/
    Response.new(response, true)
  else
    Response.new(response, false)
  end
rescue InternalError => e
  Response.new(e.message, false)
ensure
  t.close
end

#rename(old_filename, new_filename) ⇒ Object


129
130
131
132
133
134
135
136
137
138
# File 'lib/sambal/client.rb', line 129

def rename(old_filename, new_filename)
  response = ask_wrapped 'rename', [old_filename, new_filename]
  if response =~ /renaming\sfile/ # "renaming" reponse only exist if has error
    Response.new(response, false)
  else
    Response.new(response, true)
  end
rescue InternalError => e
  Response.new(e.message, false)
end

#rmdir(dir) ⇒ Object


178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/sambal/client.rb', line 178

def rmdir(dir)
  response = cd dir
  return response if response.failure?
  begin
    ls.each do |name, meta|
      if meta[:type]==:file
        response = del name
      elsif meta[:type]==:directory && !(name =~ /^\.+$/)
        response = rmdir(name)
      end
      raise InternalError.new response.message if response && response.failure?
    end
    cd '..'
    response = ask_wrapped 'rmdir', dir
    next_line = response.split("\n")[1]
    if next_line =~ /^smb:.*\\>/
      Response.new(response, true)
    else
      Response.new(response, false)
    end
  rescue InternalError => e
    Response.new(e.message, false)
  end
end

#wrap_filenames(cmd, filenames) ⇒ Object


269
270
271
272
273
# File 'lib/sambal/client.rb', line 269

def wrap_filenames(cmd,filenames)
  filenames = [filenames] unless filenames.kind_of?(Array)
  filenames.map!{ |filename| "\"#{filename}\"" }
  [cmd,filenames].flatten.join(' ')
end