summaryrefslogtreecommitdiff
path: root/libs/samba/src/main/cpp/samba.cpp
blob: 7b83eb485c4e5d40e8c8ca82b711ead0aa021bbb (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
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
246
247
248
249
250
251
252
253
254
255
256
257
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
#include <cassert>
#include <jni.h>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>

#include "jni.hpp"
#include "libsmb2.h"

namespace {

jni::LocalRef<jobject> CreateDirEntry(JNIEnv* env, const std::string& name, const smb2_stat_64& stat);

class Dir {
 public:
  Dir(std::shared_ptr<smb2_context> context, smb2dir* dir) : context_(std::move(context)), dir_(dir) {
    assert(context_ && dir_);
  }

  ~Dir() {
    smb2_closedir(context_.get(), dir_);
  }

  Dir(const Dir&) = delete;
  Dir& operator=(const Dir&) = delete;

  jni::LocalRef<jobjectArray> List(JNIEnv* env, const jni::Ref<jclass>& dir_entry_clazz) {
    smb2_rewinddir(context_.get(), dir_);
    std::vector<jni::LocalRef<jobject>> tmp;
    while (auto* ent = smb2_readdir(context_.get(), dir_)) {
      // Skip . and .. entries.
      if (ent->name[0] == '.' && (ent->name[1] == '\0' || (ent->name[1] == '.' && ent->name[2] == '\0'))) continue;
      auto obj = CreateDirEntry(env, ent->name, ent->st);
      if (obj) {
        tmp.push_back(std::move(obj));
      }
    }
    return jni::CreateArray(env, dir_entry_clazz, std::move(tmp));
  }

 private:
  std::shared_ptr<smb2_context> context_;
  smb2dir* const dir_;
};

class Url {
 public:
  explicit Url(smb2_url* url) : url_(url) {
    assert(url_);
  }

  ~Url() {
    smb2_destroy_url(url_);
  }

  Url(const Url&) = delete;
  Url& operator=(const Url&) = delete;

  [[nodiscard]] const char* path() const { return url_->path; }
  [[nodiscard]] const char* server() const { return url_->server; }
  [[nodiscard]] const char* share() const { return url_->share; }
  [[nodiscard]] const char* user() const { return url_->user; }

 private:
  smb2_url* url_;
};

class Context {
 public:
  explicit Context(int timeout) : context_(smb2_init_context(), ContextDeleter{}) {
    smb2_set_timeout(context_.get(), timeout);
  }
  ~Context() = default;

  Context(const Context&) = delete;
  Context& operator=(const Context&) = delete;

  [[nodiscard]] std::unique_ptr<Url> ParseUrl(const std::string& url) {
    auto* ptr = smb2_parse_url(context_.get(), url.c_str());
    return ptr ? std::make_unique<Url>(ptr): nullptr;
  }

  bool Connect(const Url& url, const std::optional<std::string>& username, const std::optional<std::string>& password) {
    if (password.has_value()) smb2_set_password(context_.get(), password->c_str());
    auto* user = username.has_value() ? username->c_str() : url.user();
    return smb2_connect_share(context_.get(), url.server(), url.share(), user) == 0;
  }

  [[nodiscard]] std::string_view GetError() {
    return smb2_get_error(context_.get());
  }

  [[nodiscard]] std::unique_ptr<Dir> OpenDir(const std::string& path) {
    auto* ptr = smb2_opendir(context_.get(), path.c_str());
    return ptr ? std::make_unique<Dir>(context_, ptr) : nullptr;
  }

  [[nodiscard]] jni::LocalRef<jobject> Entry(JNIEnv* env, const std::string& path) {
    struct smb2_stat_64 stat; // NOLINT(*-pro-type-member-init)
    auto ret = smb2_stat(context_.get(), path.c_str(), &stat);
    if (ret) return {env, nullptr};
    auto slash = path.find_last_of('/');
    return CreateDirEntry(env, slash == std::string::npos ? path : path.substr(slash + 1), stat);
  }

  bool MakeDir(const std::string& path) {
    return smb2_mkdir(context_.get(), path.c_str()) == 0;
  }

  bool RemoveDir(const std::string& path) {
    return smb2_rmdir(context_.get(), path.c_str()) == 0;
  }

  bool Unlink(const std::string& path) {
    return smb2_unlink(context_.get(), path.c_str()) == 0;
  }

  std::optional<std::string> ReadLink(const std::string& path) {
    // Good to start with a fairly small size as current implementation
    // of smb2_readlink uses strncpy, which pads the whole unused buffer
    // with zeros.
    uint32_t bufsize = 256;
    std::vector<char> buf;
    while (true) {
      buf.resize(bufsize);
      auto ret = smb2_readlink(context_.get(), path.c_str(), buf.data(), bufsize);
      if (ret != 0)
        return std::nullopt;
      // smb2_readlink uses strncpy, so if actual path was larger than bufsize
      // there will be no terminating zero.
      auto it = std::find(buf.begin(), buf.end(), '\0');
      if (it != buf.end())
        return std::string(buf.begin(), it);
      const auto previous = bufsize;
      bufsize *= 2;
      // Check for bufsize (a uint32_t) overflow.
      if (bufsize <= previous)
        return std::nullopt;
    }
  }

 private:
  struct ContextDeleter {
    void operator()(smb2_context* context) {
      smb2_destroy_context(context);
    }
  };

  std::shared_ptr<smb2_context> context_;
};

jlong nativeContextNew(JNIEnv* env, jclass clazz, jint timeout) {
  return reinterpret_cast<jlong>(new Context(static_cast<int>(timeout)));
}

void nativeContextDestroy(JNIEnv* env, jclass clazz, jlong ptr) {
  delete reinterpret_cast<Context*>(ptr);
}

jlong nativeContextParseUrl(JNIEnv* env, jclass clazz, jlong ptr, jstring url) {
  return reinterpret_cast<jlong>(reinterpret_cast<Context*>(ptr)->ParseUrl(jni::StringToUTF8(env, jni::ParamRef(env, url))).release());
}

jboolean nativeContextConnect(JNIEnv* env, jclass clazz, jlong context_ptr, jlong url_ptr, jstring j_username, jstring j_password) {
  auto* url = reinterpret_cast<Url*>(url_ptr);
  if (!url) return JNI_FALSE;
  std::optional<std::string> username;
  std::optional<std::string> password;
  if (j_username) username = jni::StringToUTF8(env, jni::ParamRef<jstring>(env, j_username));
  if (j_password) password = jni::StringToUTF8(env, jni::ParamRef<jstring>(env, j_password));
  return reinterpret_cast<Context*>(context_ptr)->Connect(*url, username, password) ? JNI_TRUE : JNI_FALSE;
}

jstring nativeContextGetError(JNIEnv* env, jclass clazz, jlong ptr) {
  return jni::UTF8ToString(env, std::string(reinterpret_cast<Context*>(ptr)->GetError())).release();
}

jlong nativeContextOpenDir(JNIEnv* env, jclass clazz, jlong ptr, jstring path) {
  return reinterpret_cast<jlong>(reinterpret_cast<Context*>(ptr)->OpenDir(jni::StringToUTF8(env, jni::ParamRef<jstring>(env, path))).release());
}

jobject nativeContextEntry(JNIEnv* env, jclass clazz, jlong ptr, jstring path) {
  return reinterpret_cast<Context*>(ptr)->Entry(env, jni::StringToUTF8(env, jni::ParamRef<jstring>(env, path))).release();
}

jboolean nativeContextMakeDir(JNIEnv* env, jclass clazz, jlong ptr, jstring path) {
  return reinterpret_cast<Context*>(ptr)->MakeDir(jni::StringToUTF8(env, jni::ParamRef<jstring>(env, path))) ? JNI_TRUE : JNI_FALSE;
}

jboolean nativeContextRemoveDir(JNIEnv* env, jclass clazz, jlong ptr, jstring path) {
  return reinterpret_cast<Context*>(ptr)->RemoveDir(jni::StringToUTF8(env, jni::ParamRef<jstring>(env, path))) ? JNI_TRUE : JNI_FALSE;
}

jboolean nativeContextUnlink(JNIEnv* env, jclass clazz, jlong ptr, jstring path) {
  return reinterpret_cast<Context*>(ptr)->Unlink(jni::StringToUTF8(env, jni::ParamRef<jstring>(env, path))) ? JNI_TRUE : JNI_FALSE;
}

jstring nativeContextReadLink(JNIEnv* env, jclass clazz, jlong ptr, jstring path) {
  auto ret = reinterpret_cast<Context*>(ptr)->ReadLink(jni::StringToUTF8(env, jni::ParamRef<jstring>(env, path)));
  if (ret.has_value())
    return jni::UTF8ToString(env, ret.value()).release();
  return nullptr;
}

void nativeUrlDestroy(JNIEnv* env, jclass clazz, jlong ptr) {
  delete reinterpret_cast<Url*>(ptr);
}

jstring nativeUrlPath(JNIEnv* env, jclass clazz, jlong ptr) {
  return jni::UTF8ToString(env, std::string(reinterpret_cast<Url*>(ptr)->path())).release();
}

void nativeDirDestroy(JNIEnv* env, jclass clazz, jlong ptr) {
  delete reinterpret_cast<Dir*>(ptr);
}

jni::GlobalRef<jclass> g_DirEntryClass(nullptr, nullptr);

jobjectArray nativeDirList(JNIEnv* env, jclass clazz, jlong ptr) {
  return reinterpret_cast<Dir*>(ptr)->List(env, g_DirEntryClass).release();
}

jni::GlobalRef<jclass> g_NativeSambaClass(nullptr, nullptr);
jmethodID g_CreateDirEntry;

void RegisterSamba(JNIEnv* env) {
  auto clazz = jni::FindClass(env, "org/the_jk/cleversync/io/samba/NativeSamba");
  ABORT_IF_NULL(env, clazz);
  auto dir_entry_clazz = jni::FindClass(env, "org/the_jk/cleversync/io/samba/NativeSamba$DirEntry");
  ABORT_IF_NULL(env, dir_entry_clazz);
  static const JNINativeMethod methods[] = {
      { "nativeContextNew", "(I)J", reinterpret_cast<void*>(&nativeContextNew) },
      { "nativeContextDestroy", "(J)V", reinterpret_cast<void*>(&nativeContextDestroy) },
      { "nativeContextParseUrl", "(JLjava/lang/String;)J", reinterpret_cast<void*>(&nativeContextParseUrl) },
      { "nativeContextConnect", "(JJLjava/lang/String;Ljava/lang/String;)Z", reinterpret_cast<void*>(&nativeContextConnect) },
      { "nativeContextGetError", "(J)Ljava/lang/String;", reinterpret_cast<void*>(&nativeContextGetError) },
      { "nativeContextOpenDir", "(JLjava/lang/String;)J", reinterpret_cast<void*>(&nativeContextOpenDir) },
      { "nativeContextEntry", "(JLjava/lang/String;)Lorg/the_jk/cleversync/io/samba/NativeSamba$DirEntry;", reinterpret_cast<void*>(&nativeContextEntry) },
      { "nativeContextMakeDir", "(JLjava/lang/String;)Z", reinterpret_cast<void*>(&nativeContextMakeDir) },
      { "nativeContextRemoveDir", "(JLjava/lang/String;)Z", reinterpret_cast<void*>(&nativeContextRemoveDir) },
      { "nativeContextUnlink", "(JLjava/lang/String;)Z", reinterpret_cast<void*>(&nativeContextUnlink) },
      { "nativeContextReadLink", "(JLjava/lang/String;)Ljava/lang/String;", reinterpret_cast<void*>(&nativeContextReadLink) },

      { "nativeUrlDestroy", "(J)V", reinterpret_cast<void*>(&nativeUrlDestroy) },
      { "nativeUrlPath", "(J)Ljava/lang/String;", reinterpret_cast<void*>(&nativeUrlPath) },

      { "nativeDirDestroy", "(J)V", reinterpret_cast<void*>(&nativeDirDestroy) },
      { "nativeDirList", "(J)[Lorg/the_jk/cleversync/io/samba/NativeSamba$DirEntry;", reinterpret_cast<void*>(&nativeDirList) },
  };
  auto ret = env->RegisterNatives(clazz.get(), methods, sizeof(methods) / sizeof(methods[0]));
  ABORT_IF_NOT_OK(ret);

  g_CreateDirEntry = env->GetStaticMethodID(clazz.get(), "createDirEntry", "(Ljava/lang/String;IJJ)Lorg/the_jk/cleversync/io/samba/NativeSamba$DirEntry;");
  ABORT_IF_NULL(env, g_CreateDirEntry);
  g_NativeSambaClass = clazz;
  g_DirEntryClass = dir_entry_clazz;
}

jni::LocalRef<jobject> CreateDirEntry(JNIEnv* env, const std::string& name, const smb2_stat_64& stat) {
  auto j_name = jni::UTF8ToString(env, name);
  // Kotlin size casts Long to ULong
  auto size = static_cast<jlong>(stat.smb2_size);
  auto last_modified = static_cast<jlong>(stat.smb2_mtime);
  jint type;
  switch (stat.smb2_type) {
    case SMB2_TYPE_DIRECTORY:
      type = 0;
      break;
    case SMB2_TYPE_FILE:
      type = 1;
      break;
    case SMB2_TYPE_LINK:
      type = 2;
      break;
    default:
      return {env, nullptr};
  }

  return jni::CallStaticObjectMethod<jobject>(env, g_NativeSambaClass, g_CreateDirEntry, j_name.get(), type, size, last_modified);
}

}  // namespace

jint JNI_OnLoad(JavaVM *vm, void *reserved) {
  auto* env = jni::OnLoad(vm);

  RegisterSamba(env);

  return jni::JNI_VERSION;
}