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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use super::*;
use crate::networking_types::NetworkingIdentity;
#[cfg(test)]
use serial_test::serial;
use std::net::Ipv4Addr;

/// The main entry point into the steam client for servers.
///
/// This provides access to all of the steamworks api that
/// servers can use.
#[derive(Clone)]
pub struct Server {
    inner: Arc<Inner<ServerManager>>,
    server: *mut sys::ISteamGameServer,
}

unsafe impl Send for Server {}
unsafe impl Sync for Server {}

/// Used to set the mode that a gameserver will run in
pub enum ServerMode {
    /// Don't authenticate user logins.
    ///
    /// The server will not appear on the server list
    NoAuthentication,
    /// Authenticate users
    ///
    /// The server will appear on the server list and
    /// VAC will not be run on clients.
    Authentication,
    /// Authenticate users and use anti-cheat.
    ///
    /// The server will appear on the server list and
    /// VAC will be run on clients.
    AuthenticationAndSecure,
}

impl Server {
    fn steam_game_server_init_ex(
        un_ip: std::ffi::c_uint,
        us_game_port: std::ffi::c_ushort,
        us_query_port: std::ffi::c_ushort,
        e_server_mode: EServerMode,
        pch_version_string: *const c_char,
        p_out_err_msg: *mut SteamErrMsg,
    ) -> ESteamAPIInitResult {
        let versions: Vec<&[u8]> = vec![
            sys::STEAMUTILS_INTERFACE_VERSION,
            sys::STEAMNETWORKINGUTILS_INTERFACE_VERSION,
            sys::STEAMGAMESERVER_INTERFACE_VERSION,
            sys::STEAMGAMESERVERSTATS_INTERFACE_VERSION,
            sys::STEAMHTTP_INTERFACE_VERSION,
            sys::STEAMINVENTORY_INTERFACE_VERSION,
            sys::STEAMNETWORKING_INTERFACE_VERSION,
            sys::STEAMNETWORKINGMESSAGES_INTERFACE_VERSION,
            sys::STEAMNETWORKINGSOCKETS_INTERFACE_VERSION,
            sys::STEAMUGC_INTERFACE_VERSION,
            b"\0",
        ];

        let merged_versions: Vec<u8> = versions.into_iter().flatten().cloned().collect();
        let merged_versions_ptr = merged_versions.as_ptr() as *const ::std::os::raw::c_char;

        return unsafe {
            sys::SteamInternal_GameServer_Init_V2(
                un_ip,
                us_game_port,
                us_query_port,
                e_server_mode,
                pch_version_string,
                merged_versions_ptr,
                p_out_err_msg,
            )
        };
    }

    /// Attempts to initialize the steamworks api and returns
    /// a server to access the rest of the api.
    ///
    /// This should only ever have one instance per a program.
    ///
    /// Currently the steamworks api doesn't support IPv6.
    ///
    /// # Errors
    ///
    /// This can fail if:
    /// * The steam client isn't running
    /// * The app ID of the game couldn't be determined.
    ///
    ///   If the game isn't being run through steam this can be provided by
    ///   placing a `steam_appid.txt` with the ID inside in the current
    ///   working directory
    /// * The game isn't running on the same user/level as the steam client
    /// * The user doesn't own a license for the game.
    /// * The app ID isn't completely set up.
    pub fn init(
        ip: Ipv4Addr,
        game_port: u16,
        query_port: u16,
        server_mode: ServerMode,
        version: &str,
    ) -> SIResult<(Server, SingleClient<ServerManager>)> {
        unsafe {
            let version = CString::new(version).unwrap();

            // let internal_check_interface_versions =

            let raw_ip: u32 = ip.into();
            let server_mode = match server_mode {
                ServerMode::NoAuthentication => sys::EServerMode::eServerModeNoAuthentication,
                ServerMode::Authentication => sys::EServerMode::eServerModeAuthentication,
                ServerMode::AuthenticationAndSecure => {
                    sys::EServerMode::eServerModeAuthenticationAndSecure
                }
            };

            let mut err_msg: sys::SteamErrMsg = [0; 1024];
            let result = Self::steam_game_server_init_ex(
                raw_ip,
                game_port,
                query_port,
                server_mode,
                version.as_ptr(),
                &mut err_msg,
            );

            if result != sys::ESteamAPIInitResult::k_ESteamAPIInitResult_OK {
                return Err(SteamAPIInitError::from_result_and_message(result, err_msg));
            }

            sys::SteamAPI_ManualDispatch_Init();
            let server_raw = sys::SteamAPI_SteamGameServer_v015();
            let server = Arc::new(Inner {
                _manager: ServerManager { _priv: () },
                callbacks: Mutex::new(Callbacks {
                    callbacks: HashMap::new(),
                    call_results: HashMap::new(),
                }),
                networking_sockets_data: Mutex::new(NetworkingSocketsData {
                    sockets: Default::default(),
                    independent_connections: Default::default(),
                    connection_callback: Default::default(),
                }),
            });
            Ok((
                Server {
                    inner: server.clone(),
                    server: server_raw,
                },
                SingleClient {
                    inner: server,
                    _not_sync: PhantomData,
                },
            ))
        }
    }

    /// Registers the passed function as a callback for the
    /// given type.
    ///
    /// The callback will be run on the thread that `run_callbacks`
    /// is called when the event arrives.
    pub fn register_callback<C, F>(&self, f: F) -> CallbackHandle<ServerManager>
    where
        C: Callback,
        F: FnMut(C) + 'static + Send,
    {
        unsafe { register_callback(&self.inner, f) }
    }

    /// Returns the steam id of the current server
    pub fn steam_id(&self) -> SteamId {
        unsafe { SteamId(sys::SteamAPI_ISteamGameServer_GetSteamID(self.server)) }
    }

    /// Retrieve an authentication session ticket that can be sent
    /// to an entity that wishes to verify you.
    ///
    /// This ticket should not be reused.
    ///
    /// When creating ticket for use by the web API you should wait
    /// for the `AuthSessionTicketResponse` event before trying to
    /// use the ticket.
    ///
    /// When the multiplayer session terminates you must call
    /// `cancel_authentication_ticket`
    pub fn authentication_session_ticket_with_steam_id(
        &self,
        steam_id: SteamId,
    ) -> (AuthTicket, Vec<u8>) {
        self.authentication_session_ticket(NetworkingIdentity::new_steam_id(steam_id))
    }
    pub fn authentication_session_ticket(
        &self,
        network_identity: NetworkingIdentity,
    ) -> (AuthTicket, Vec<u8>) {
        unsafe {
            let mut ticket = vec![0; 1024];
            let mut ticket_len = 0;
            let auth_ticket = sys::SteamAPI_ISteamGameServer_GetAuthSessionTicket(
                self.server,
                ticket.as_mut_ptr() as *mut _,
                1024,
                &mut ticket_len,
                network_identity.as_ptr(),
            );
            ticket.truncate(ticket_len as usize);
            (AuthTicket(auth_ticket), ticket)
        }
    }

    /// Cancels an authentication session ticket received from
    /// `authentication_session_ticket`.
    ///
    /// This should be called when you are no longer playing with
    /// the specified entity.
    pub fn cancel_authentication_ticket(&self, ticket: AuthTicket) {
        unsafe {
            sys::SteamAPI_ISteamGameServer_CancelAuthTicket(self.server, ticket.0);
        }
    }

    /// Authenticate the ticket from the steam ID to make sure it is
    /// valid and not reused.
    ///
    /// A `ValidateAuthTicketResponse` callback will be fired if
    /// the entity goes offline or cancels the ticket.
    ///
    /// When the multiplayer session terminates you must call
    /// `end_authentication_session`
    pub fn begin_authentication_session(
        &self,
        user: SteamId,
        ticket: &[u8],
    ) -> Result<(), AuthSessionError> {
        unsafe {
            let res = sys::SteamAPI_ISteamGameServer_BeginAuthSession(
                self.server,
                ticket.as_ptr() as *const _,
                ticket.len() as _,
                user.0,
            );
            Err(match res {
                sys::EBeginAuthSessionResult::k_EBeginAuthSessionResultOK => return Ok(()),
                sys::EBeginAuthSessionResult::k_EBeginAuthSessionResultInvalidTicket => {
                    AuthSessionError::InvalidTicket
                }
                sys::EBeginAuthSessionResult::k_EBeginAuthSessionResultDuplicateRequest => {
                    AuthSessionError::DuplicateRequest
                }
                sys::EBeginAuthSessionResult::k_EBeginAuthSessionResultInvalidVersion => {
                    AuthSessionError::InvalidVersion
                }
                sys::EBeginAuthSessionResult::k_EBeginAuthSessionResultGameMismatch => {
                    AuthSessionError::GameMismatch
                }
                sys::EBeginAuthSessionResult::k_EBeginAuthSessionResultExpiredTicket => {
                    AuthSessionError::ExpiredTicket
                }
                _ => unreachable!(),
            })
        }
    }

    /// Ends an authentication session that was started with
    /// `begin_authentication_session`.
    ///
    /// This should be called when you are no longer playing with
    /// the specified entity.
    pub fn end_authentication_session(&self, user: SteamId) {
        unsafe {
            sys::SteamAPI_ISteamGameServer_EndAuthSession(self.server, user.0);
        }
    }

    /// Sets the game product identifier. This is currently used by the master server for version
    /// checking purposes. Converting the games app ID to a string for this is recommended.
    ///
    /// This is required for all game servers and can only be set before calling
    /// log_on() or log_on_anonymous().
    pub fn set_product(&self, product: &str) {
        let product = CString::new(product).unwrap();
        unsafe {
            sys::SteamAPI_ISteamGameServer_SetProduct(self.server, product.as_ptr() as *const _);
        }
    }

    /// Sets the game description. Setting this to the full name of your game is recommended.
    ///
    /// This is required for all game servers and can only be set before calling
    /// log_on() or log_on_anonymous().
    pub fn set_game_description(&self, desc: &str) {
        let desc = CString::new(desc).unwrap();
        unsafe {
            sys::SteamAPI_ISteamGameServer_SetGameDescription(self.server, desc.as_ptr());
        }
    }

    /// Sets whether this server is dedicated or a listen server.
    pub fn set_dedicated_server(&self, dedicated: bool) {
        unsafe {
            sys::SteamAPI_ISteamGameServer_SetDedicatedServer(self.server, dedicated);
        }
    }

    /// Login to a generic anonymous account
    pub fn log_on_anonymous(&self) {
        unsafe {
            sys::SteamAPI_ISteamGameServer_LogOnAnonymous(self.server);
        }
    }

    /// If active, updates the master server with this server's presence so players can find it via
    /// the steam matchmaking/server browser interfaces.
    pub fn enable_heartbeats(&self, active: bool) {
        unsafe {
            sys::SteamAPI_ISteamGameServer_SetAdvertiseServerActive(self.server, active);
        }
    }

    /// If your game is a "mod," pass the string that identifies it.  The default is an empty
    /// string, meaning this application is the original game, not a mod.
    pub fn set_mod_dir(&self, mod_dir: &str) {
        let mod_dir = CString::new(mod_dir).unwrap();
        unsafe {
            sys::SteamAPI_ISteamGameServer_SetModDir(self.server, mod_dir.as_ptr());
        }
    }

    /// Set name of map to report in the server browser
    pub fn set_map_name(&self, map_name: &str) {
        let map_name = CString::new(map_name).unwrap();
        unsafe {
            sys::SteamAPI_ISteamGameServer_SetMapName(self.server, map_name.as_ptr());
        }
    }

    /// Set the name of server as it will appear in the server browser
    pub fn set_server_name(&self, server_name: &str) {
        let server_name = CString::new(server_name).unwrap();
        unsafe {
            sys::SteamAPI_ISteamGameServer_SetMapName(self.server, server_name.as_ptr());
        }
    }

    /// Sets the maximum number of players allowed on the server at once.
    ///
    /// This value may be changed at any time.
    pub fn set_max_players(&self, count: i32) {
        unsafe {
            sys::SteamAPI_ISteamGameServer_SetMaxPlayerCount(self.server, count);
        }
    }

    /// Returns an accessor to the steam UGC interface (steam workshop)
    ///
    /// **For this to work properly, you need to call `UGC::init_for_game_server()`!**
    pub fn ugc(&self) -> UGC<ServerManager> {
        unsafe {
            let ugc = sys::SteamAPI_SteamGameServerUGC_v018();
            debug_assert!(!ugc.is_null());
            UGC {
                ugc,
                inner: self.inner.clone(),
            }
        }
    }

    /* TODO: Buggy currently?
    /// Returns an accessor to the steam apps interface
    pub fn apps(&self) -> Apps<ServerManager> {
        unsafe {
            let apps = sys::steam_rust_get_server_apps();
            debug_assert!(!apps.is_null());
            Apps {
                apps: apps,
                _inner: self.inner.clone(),
            }
        }
    }
    */
}

#[test]
#[serial]
fn test() {
    let (server, single) = Server::init(
        [127, 0, 0, 1].into(),
        23334,
        23335,
        ServerMode::Authentication,
        "0.0.1",
    )
    .unwrap();

    println!("{:?}", server.steam_id());

    server.set_product("steamworks-rs test");
    server.set_game_description("basic server test");
    server.set_dedicated_server(true);
    server.log_on_anonymous();

    println!("{:?}", server.steam_id());

    let _cb = server.register_callback(|v: AuthSessionTicketResponse| {
        println!("Got auth ticket response: {:?}", v.result)
    });
    let _cb = server.register_callback(|v: ValidateAuthTicketResponse| {
        println!("Got validate auth ticket response: {:?}", v)
    });

    let id = server.steam_id();
    let (auth, ticket) = server.authentication_session_ticket_with_steam_id(id);

    println!("{:?}", server.begin_authentication_session(id, &ticket));

    for _ in 0..20 {
        single.run_callbacks();
        ::std::thread::sleep(::std::time::Duration::from_millis(50));
    }

    println!("END");

    server.cancel_authentication_ticket(auth);

    for _ in 0..20 {
        single.run_callbacks();
        ::std::thread::sleep(::std::time::Duration::from_millis(50));
    }

    server.end_authentication_session(id);
}

/// Manages keeping the steam api active for servers
pub struct ServerManager {
    _priv: (),
}

unsafe impl Manager for ServerManager {
    unsafe fn get_pipe() -> sys::HSteamPipe {
        sys::SteamGameServer_GetHSteamPipe()
    }
}

impl Drop for ServerManager {
    fn drop(&mut self) {
        unsafe {
            sys::SteamGameServer_Shutdown();
        }
    }
}