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
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright 2020-2021 Ian Jackson and contributors to Otter
// SPDX-License-Identifier: AGPL-3.0-or-later
// There is NO WARRANTY.

use crate::prelude::*;

#[derive(Debug,Serialize,Deserialize)]
pub enum MgmtCommand {
  Noop,
  SetSuperuser(bool),
  SetRestrictedSshScope { key: sshkeys::KeySpec },

  CreateAccount(AccountDetails),
  UpdateAccount(AccountDetails),
  DeleteAccount(AccountName),
  ListAccounts { all: Option<bool> },

  SelectAccount(AccountName), // success does not mean account exists
  CheckAccount, // success *does* mean account exists and we have access

  CreateGame {
    game: InstanceName,
    insns: Vec<MgmtGameInstruction>,
  },
  ListGames { all: Option<bool> },
  AlterGame {
    game: InstanceName,
    insns: Vec<MgmtGameInstruction>,
    how: MgmtGameUpdateMode,
  },
  DestroyGame {
    game: InstanceName,
  },

  ClearBundles {
    game: InstanceName,
  },
  UploadBundle {
    game: InstanceName,
    size: usize,
    hash: bundles::Hash,
    kind: bundles::Kind,
    #[serde(default)] progress: ProgressUpdateMode,
  },
  ListBundles {
    game: InstanceName,
  },
  DownloadBundle {
    game: InstanceName,
    id: bundles::Id,
  },

  LibraryListLibraries {
    game: InstanceName,
  },
  LibraryListByGlob {
    game: InstanceName,
    lib: Option<String>,
    pat: String,
  },

  SshListKeys,
  SshAddKey { akl: sshkeys::AuthkeysLine },
  SshDeleteKey { index: usize, id: sshkeys::Id },
  ThisConnAuthBy, // -> Fine or SshKeySpec
  SshReinstallKeys, // managment only

  LoadFakeRng(Vec<String>),
}

//---------- Accounts file ----------

#[derive(Debug,Clone,Hash,Eq,PartialEq)]
#[derive(Serialize,Deserialize)]
pub struct SshFingerprint(pub String);

#[derive(Debug,Serialize,Deserialize)]
pub struct AccountDetails {
  pub account: AccountName,
  pub nick: Option<String>,
  pub timezone: Option<String>,
  pub layout: Option<PresentationLayout>,
  #[serde(flatten)]
  pub access: Option<Box<dyn PlayerAccessSpec>>,
//  pub invite: Acl<AccountPerm>,   todo
}

//#[derive(Debug,Clone,Copy,Serialize,Deserialize)]
//enum AccountPerm {
//  InviteToGame,
//  GameRunnerResetToken,
//}


#[derive(Debug,Serialize,Deserialize)]
pub enum MgmtResponse {
  Fine,
  Progress(ProgressInfo<'static>),
  Error { error: MgmtError },
  AlterGame { error: Option<MgmtError>, responses: Vec<MgmtGameResponse> },
  AccountsList(Vec<Arc<AccountName>>),
  GamesList(Vec<Arc<InstanceName>>),
  Libraries(Vec<LibraryEnquiryData>),
  LibraryItems(Vec<ItemEnquiryData>),
  Bundles { bundles: MgmtBundleList },
  Bundle { bundle: bundles::Id },
  SshKeys(Vec<sshkeys::MgmtKeyReport>),
  SshKeyAdded { index: usize, id: sshkeys::Id },
  ThisConnAuthBy(MgmtThisConnAuthBy),
}

pub type MgmtBundleList = BTreeMap<bundles::Id, bundles::State>;

#[derive(Debug,Clone,Serialize,Deserialize)]
pub enum MgmtThisConnAuthBy {
  Local,
  Ssh { key: sshkeys::KeySpec },
}

#[derive(Debug,Serialize,Deserialize)]
pub enum MgmtGameInstruction {
  Noop,
  Info,
  SetTableSize(Pos),
  SetTableColour(ColourSpec),

  InsnMark(Box<[u8]>),
  /// For testing, mostly.
  Synch, SynchLog,
  /// For testing only
  PieceIdLookupFwd { piece: PieceId, player: PlayerId, },
  /// For testing only
  PieceIdLookupRev { vpid: VisiblePieceId, player: PlayerId, },

  ListPieces,
  AddPieces(PiecesSpec),
  DeletePiece(PieceId),
  DeletePieceAlias(String),
  DefinePieceAlias { alias: String, target: Box<dyn PieceSpec> },

  ClearGame { },
  ResetFromNamedSpec { spec: String },
  ResetFromGameSpec { spec_toml: String },

  ResetPlayerAccess(PlayerId),
  RedeliverPlayerAccess(PlayerId),

  JoinGame { details: MgmtPlayerDetails },
  UpdatePlayer { player: PlayerId, details: MgmtPlayerDetails },
  LeaveGame(PlayerId),

  SetLinks(HashMap<LinkKind, UrlSpec>),
  RemoveLink { kind: LinkKind },
  SetLink { kind: LinkKind, url: UrlSpec },

  ClearLog,
  SetACL { acl: Acl<TablePermission> },
  // RemovePlayer { player: PlayerId },  todo, does a special setacl
}

#[derive(Debug,Serialize,Deserialize)]
pub struct MgmtPlayerDetails {
  pub nick: Option<String>,
}

#[derive(Debug,Serialize,Deserialize)]
pub enum MgmtGameResponse {
  Fine,
  Info(MgmtGameResponseGameInfo),
  InsnMark(Box<[u8]>),
  InsnExpanded,
  Synch(Generation),

  InternalPieceId(Option<PieceId>),
  VisiblePieceId(Option<VisiblePieceId>),

  Pieces {
    pieces: Vec<MgmtGamePieceInfo>,
    pcaliases: BTreeSet<String>,
  },

  JoinGame {
    nick: String,
    player: PlayerId,
    token: AccessTokenReport,
  },
  PlayerAccessToken(AccessTokenReport),
}

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct AccessTokenInfo { pub url: String }

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct AccessTokenReport { pub lines: Vec<String> }

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct MgmtGameResponseGameInfo {
  pub table_size: Pos,
  pub players: SecondarySlotMap<PlayerId, MgmtPlayerInfo>,
  pub links: Vec<(LinkKind, UrlSpec)>,
}

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct MgmtPlayerInfo {
  pub account: AccountName,
  pub nick: String,
}

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct MgmtGamePieceInfo {
  pub piece: PieceId,
  pub itemname: shapelib::GoodItemName,
  #[serde(flatten)]
  pub visible: Option<MgmtGamePieceVisibleInfo>,
}

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct MgmtGamePieceVisibleInfo {
  pub pos: Pos,
  pub face: FaceId,
  pub desc_html: Html,
  pub bbox: Rect,
}

#[derive(Debug,Copy,Clone,Serialize,Deserialize)]
pub enum MgmtGameUpdateMode {
  Online,
  Bulk,
}

#[derive(Debug,Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Serialize,Deserialize)]
pub enum ProgressUpdateMode {
  None,
  Simplex,
  Duplex,
}
impl Default for ProgressUpdateMode {
  fn default() -> Self { PUM::None }
}

#[derive(Debug,Clone,Error,Serialize,Deserialize)]
pub enum MgmtError {
  #[error("failed to parse protocol command: {0}")] CommandParseFailed(String),
  #[error("not authorised")]                         AuthorisationError,
  #[error("superuse authorisation requiredr")] SuperuserAuthorisationRequired,
  #[error("command requires account specified")]     SpecifyAccount,
  #[error("command requires nick specified")]        MustSpecifyNick,
  #[error("object or item already exists")]          AlreadyExists,
  #[error("game already has player with that nick")] NickCollision,
  #[error("{0}")] GameBeingDestroyed (#[from] GameBeingDestroyed),
  #[error("game not found")]                         GameNotFound,
  #[error("{0}")] AccountNotFound     (#[from] AccountNotFound),
  #[error("{0}")] PlayerNotFound      (#[from] PlayerNotFound),
  #[error("piece not found in game")]                PieceNotFound,
  #[error("limit exceeded")]                         LimitExceeded,
  #[error("server failure: {0}")]                    ServerFailure(String),
  #[error("{0}")] ZCoordinateOverflow (#[from] zcoord::Overflow),
  #[error("bad glob pattern: {pat:?}: {msg}")]
                                           BadGlob { pat: String, msg: String },
  #[error("{0}")] BadSpec             (#[from] SpecError),
  #[error("access token delivery failed: {0}")]
                  TokenDeliveryFailed (#[from] TokenDeliveryError),
  #[error("{0}")] CoordinateOverflow  (#[from] CoordinateOverflow),
  #[error("TOML syntax error: {0}")]                 TomlSyntaxError(String),
  #[error("TOML structure error: {0}")]              TomlStructureError(String),
  #[error("RNG is real, command not supported")]     RngIsReal,
  #[error("upload truncated")]                       UploadTruncated,
  #[error("upload corrupted")]                       UploadCorrupted,
  #[error("too many bundles")]                       TooManyBundles,
  #[error("bad bundle: {0}")]                        BadBundle(String),
  #[error("bundle not found")]                       BundleNotFound,
  #[error("bundle(s) in use, cannot clear ({0})")]   BundlesInUse(String),
  #[error("game spec not found")]                    GameSpecNotFound,
  #[error("game contains invalid UTF-8")]            GameSpecInvalidData,
  #[error("idle timeout waiting for mgmt command")]  IdleTimeout,
  #[error("upload took too long (timed out)")]       UploadTimeout,
  #[error("ssh keys are only for main subaccount")]  NoSshKeysForSubaccount,
  #[error("ssh key not found")]                      SshKeyNotFound,
  #[error("ssh key id default, ie invalid")]         InvalidSshKeyId,
  #[error("ssh key invalid: {0}")] InvalidSshKey(#[from] sshkeys::KeyError),
  #[error("command forbides account specified")]     AccountSpecified,
}

impl AccountDetails {
  pub fn default(account: AccountName) -> AccountDetails { AccountDetails {
    account,
    nick: None, timezone: None, layout: None, access: None,
  } }
}

impl From<InternalError> for MgmtError {
  fn from(e: InternalError) -> MgmtError {
    MgmtError::ServerFailure(format!("internal error: {}", &e))
  }
}

impl AccessTokenInfo {
  pub fn report(self) -> Vec<String> {
    vec![
      "Game access url:".to_string(),
      self.url,
    ]
  }
}