/// <summary> /// Read /// </summary> /// <param name="node">The node</param> /// <param name="offset">The offset</param> /// <param name="size">The size</param> /// <param name="buffer">The buffer</param> /// <returns>The amount of bytes written</returns> private static unsafe uint infoReadImpl(Node node, uint offset, uint size, byte[] buffer) { // Check if the task still exists IDCookie cookie = (IDCookie)node.Cookie; Task task = Tasking.GetTaskByPID(cookie.ID); if (task == null) { return(0); } ProcFSInfo info = new ProcFSInfo(); info.Uptime = task.Uptime; info.Priority = (int)task.Priority; info.ThreadCount = task.ThreadCount; info.Pid = task.PID; // Copy name and cmdline String.CopyTo(info.Name, task.Name, 64); String.CopyTo(info.CMDLine, task.CMDLine, 256); if (size > sizeof(ProcFSInfo)) { size = (uint)sizeof(ProcFSInfo); } Memory.Memcpy(Util.ObjectToVoidPtr(buffer), &info, (int)size); return(size); }
/// <summary> /// Handler for timer /// </summary> /// <param name="context">The old context</param> /// <returns>The new context</returns> private static void *timerHandler(void *context) { // Update ticks Time.SubTicks++; // One second if (Time.SubTicks == Time.TicksPerSecond) { // Update ticks Time.SubTicks = 0; Time.FullTicks++; Time.Seconds++; if (Time.Seconds == 60) { Time.Seconds = 0; Time.Minutes++; // Re-read the CMOS time every hour if (Time.Minutes == 60) { CMOS.UpdateTime(); Time.FullTicks = Time.CalculateEpochTime(); } } } // Context switch context = Tasking.Scheduler(context); SendEOI(); return(context); }
void AddNewItems() { while (parent.IsRunning()) { if (Tasking.WaitForFalseOrTimeout(parent.IsRunning, 3000).Result) { continue; } while (!toBeSold.IsEmpty) { Thread.Sleep(1000); } SpinWait.SpinUntil(() => (doNotSell || toBeSold.IsEmpty)); if (doNotSell) { //doNotSell = false; //Thread.Sleep(1000 * 60 * 2); //can't lower it due to some weird things in protocol, requires testing } else { try { Inventory inventory = Protocol.GetSteamInventory(); foreach (Inventory.SteamItem item in inventory.content) { toBeSold.Enqueue(item); } } catch (Exception ex) { Log.Error("Some error occured. Message: " + ex.Message + "\nTrace: " + ex.StackTrace); } } } }
void SetNewOrder() { while (parent.IsRunning()) { if (Tasking.WaitForFalseOrTimeout(parent.IsRunning, 1000).Result) { return; } if (needOrder.Count != 0) { NewHistoryItem item = needOrder.Dequeue(); bool took = false; try { int price = Protocol.getBestOrder(item.i_classid, item.i_instanceid); if (price != -1 && price < 30000) { __database__.EnterReadLock(); took = true; if (__database__.newDataBase[item.i_market_name].GetMedian() * MAXFROMMEDIAN - price > 30) { Protocol.SetOrder(item.i_classid, item.i_instanceid, ++price); } } } catch (Exception ex) { Log.Error("Some error occured. Message: " + ex.Message + "\nTrace: " + ex.StackTrace); } finally { if (took) { __database__.ExitReadLock(); } } } } }
/// <summary> /// FS finddir /// </summary> /// <param name="node">The node</param> /// <param name="name">The name to look for</param> /// <returns>The node</returns> private static unsafe Node rootFindDirImpl(Node node, string name) { int pid = int.Parse(name); if (pid < 0) { return(null); } Task task = Tasking.GetTaskByPID(pid); if (task == null) { return(null); } Node taskNode = new Node(); taskNode.Cookie = new IDCookie(task.PID); taskNode.Flags = NodeFlags.DIRECTORY; taskNode.FindDir = procFindDirImpl; taskNode.ReadDir = procReadDirImpl; return(taskNode); }
public ActionResult DeleteConfirmed(int id) { Tasking tasking = db.Taskings.Find(id); db.Taskings.Remove(tasking); db.SaveChanges(); return(RedirectToAction("Index")); }
void SaveDataBaseCycle() { while (parent.IsRunning()) { __database__.Save(); Tasking.WaitForFalseOrTimeout(parent.IsRunning, Consts.MINORCYCLETIMEINTERVAL).Wait(); } }
private void UnstickeredDumper() { while (!disposed) { Tasking.WaitForFalseOrTimeout(() => !disposed, 60000).Wait(); string[] lines = unstickeredCache.Dump(); File.WriteAllLines(Path.Combine("assets", "emptystickered.txt"), lines); } }
public void InventoryFetcher() { while (!WaitingForRestart) { GenericInventory inv = new GenericInventory(bot.SteamWeb); inv.load(730, new long[] { 2 }, bot.SteamUser.SteamID, "russian"); int counter = inv.descriptions.Count; if (counter != 0) //lol... { logic.cachedInventory = inv; logic.cachedTradableCount = counter; LocalRequest.PutInventory(config.Username, inv); double tradeprice = 0; int untracked = 0; logic.__database__.EnterReadLock(); try { double medianprice = 0; foreach (var item in inv.descriptions) { string quality; string runame; try { quality = item.Value.market_hash_name.Split(new char[] { '(', ')' })[1]; runame = item.Value.name + " (" + ConvertQualityToRussian(quality) + ")"; } catch { runame = item.Value.name; //??? continue; } if (logic.__database__.newDataBase.TryGetValue(runame, out Logic.BasicSalesHistory sales)) { int medPrice = sales.GetMedian(); medianprice += medPrice; if (item.Value.tradable) { tradeprice += medPrice; } } } LocalRequest.PutTradableCost(config.Username, Economy.ConvertCurrency(Economy.Currency.RUB, Economy.Currency.USD, tradeprice / 100), untracked); LocalRequest.PutMedianCost(config.Username, Economy.ConvertCurrency(Economy.Currency.RUB, Economy.Currency.USD, medianprice / 100)); } finally { logic.__database__.ExitReadLock(); } } LocalRequest.PutMoney(config.Username, protocol.GetMoney()); if (counter != 0) { Tasking.WaitForFalseOrTimeout(IsRunning, timeout: Consts.MINORCYCLETIMEINTERVAL).Wait(); //10 minutes this data is pretty much static } else { Tasking.WaitForFalseOrTimeout(IsRunning, timeout: Consts.MINORCYCLETIMEINTERVAL / 10).Wait(); //1 minute because I need to reupload inventory on failure. } } }
public ActionResult Edit([Bind(Include = "id,Name,StartDate,EndDate,Status,User")] Tasking tasking) { if (ModelState.IsValid) { db.Entry(tasking).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(tasking)); }
static void Open(object sender, EventArgs e) { died = false; opening = false; Log.Success("Connection opened!"); Tasking.Run((Action)SocketPinger, "Balancer"); socket.Send("newitems_go"); socket.Send("history_go"); //start = DateTime.Now; }
private void Delayer() { while (!bot.IsLoggedIn) { Thread.Sleep(10); } ReadyToRun = true; Tasking.Run(Restarter, botName); }
void SellFromQueue() { while (parent.IsRunning()) { if (Tasking.WaitForFalseOrTimeout(parent.IsRunning, 1000).Result) { continue; } while (refreshPrice.IsEmpty && toBeSold.IsEmpty) { Thread.Sleep(1000); } if (!refreshPrice.IsEmpty) { lock (RefreshItemsLock) { List <Tuple <string, int> > items = new List <Tuple <string, int> >(); items = new List <Tuple <string, int> >(); while (refreshPrice.TryDequeue(out TMTrade trade)) { items.Add(new Tuple <string, int>(trade.ui_id, 0)); } /*JOBject obj = */ Protocol.MassSetPriceById(items); } } else if (toBeSold.TryDequeue(out Inventory.SteamItem item)) { if (cachedInventory != null && cachedTradableCount < stopsell) { while (toBeSold.TryDequeue(out item)) { ; //clear whole queue } Protocol.RemoveAll(); continue; } int price = GetMySellPrice(item); if (price != -1) { try { string[] ui_id = item.ui_id.Split('_'); if (Protocol.SellNew(long.Parse(ui_id[1]), long.Parse(ui_id[2]), price)) { Log.Success($"New {item.i_market_name} is on sale for {price}"); } else { Log.ApiError(TMBot.RestartPriority.SmallError, "Could not sell new item, enqueuing it again."); } } catch { } } } } }
public ActionResult Create([Bind(Include = "id,Name,StartDate,EndDate,Status,User")] Tasking tasking) { if (ModelState.IsValid) { db.Taskings.Add(tasking); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(tasking)); }
/// <summary> /// Read packet from connection /// </summary> /// <param name="con"></param> /// <returns></returns> public unsafe static TCPPacketDescriptor *Read(TCPConnection con) { Queue queue = con.ReceiveQueue; while (queue.IsEmpty()) { Tasking.Yield(); } return((TCPPacketDescriptor *)con.ReceiveQueue.Pop()); }
/// <summary> /// Sends a signal to a process /// </summary> /// <param name="pid">The PID</param> /// <param name="sig">The signal</param> /// <returns>The errorcode</returns> public static ErrorCode SigSend(int pid, Signal sig) { if (pid <= 0) { return(ErrorCode.EINVAL); } Task task = Tasking.GetTaskByPID(pid); if (task == null) return(ErrorCode.ESRCH); }
static void SocketPinger() { while (!died) { try { socket.Send("ping"); } catch (Exception ex) { Log.Error("Some error occured. Message: " + ex.Message + "\nTrace: " + ex.StackTrace); } Tasking.WaitForFalseOrTimeout(() => !died, 30000).Wait(); } }
// GET: Taskings/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Tasking tasking = db.Taskings.Find(id); if (tasking == null) { return(HttpNotFound()); } return(View(tasking)); }
void ParsingCycle() { while (parent.IsRunning()) { if (ParseNewDatabase()) { Log.Success("Finished parsing new DB"); } else { Log.Error("Couldn\'t parse new DB"); } Tasking.WaitForFalseOrTimeout(parent.IsRunning, Consts.PARSEDATABASEINTERVAL).Wait(); } }
/// <summary> /// FS readdir /// </summary> /// <param name="node">The node</param> /// <param name="index">The index</param> /// <returns>The directory entry</returns> private static unsafe DirEntry *procReadDirImpl(Node node, uint index) { // Check if task still exists IDCookie cookie = (IDCookie)node.Cookie; Task task = Tasking.GetTaskByPID(cookie.ID); if (task == null) { return(null); } DirEntry *entry = (DirEntry *)Heap.Alloc(sizeof(DirEntry)); string name = null; // Index zero is the info file if (index == 0) { name = "info"; } else { int j = 0; Thread current = task.FirstThread; while (j < index - 1 && current.NextThread != task.FirstThread) { current = current.NextThread; j++; } // Last thread entry reached but index is still not reached? Stop. if (j < index - 1 && current.NextThread == task.FirstThread) { return(null); } name = current.TID.ToString(); } String.CopyTo(entry->Name, name); // A new string is only created here when index != 0 if (index != 0) { Heap.Free(name); } return(entry); }
/// <summary> /// Replaces the current process with another executable /// </summary> /// <param name="path">The path to the executable</param> /// <param name="argv">The arguments</param> /// <param name="envp">The environment path</param> /// <returns>Errorcode</returns> public static int Execve(string path, string[] argv, string[] envp) { // TODO: envp path = VFS.CreateAbsolutePath(path); int error = Loader.StartProcess(path, argv, Task.SpawnFlags.SWAP_PID); Heap.Free(path); if (error < 0) { return(error); } // We spawned a task but the current process should actually be replaced // So we must kill the current process Tasking.RemoveTaskByPID(Tasking.CurrentTask.PID); return(0); }
/// <summary> /// Read from a file descriptor /// </summary> /// <param name="descriptor">The descriptor ID</param> /// <param name="buffer">The buffer</param> /// <param name="size">The size</param> /// <returns>The amount of bytes read</returns> public static int Read(int descriptor, byte[] buffer, uint size) { FileDescriptors descriptors = Tasking.CurrentTask.FileDescriptors; Node node = descriptors.GetNode(descriptor); if (node == null) { return(-(int)ErrorCode.EBADF); } // Can't do read from a directory if ((node.Flags & NodeFlags.DIRECTORY) == NodeFlags.DIRECTORY) { return(-(int)ErrorCode.EISDIR); } bool isNonBlocking = ((node.OpenFlags & O_NONBLOCK) == O_NONBLOCK); // Wait until data is available if its blocking if (!isNonBlocking) { while (VFS.GetSize(node) == 0) { Tasking.Yield(); } } // Non-blocking but no data available? else { if (VFS.GetSize(node) == 0) { return(-(int)ErrorCode.EAGAIN); } } uint offset = descriptors.GetOffset(descriptor); uint readBytes = VFS.Read(node, offset, size, buffer); descriptors.SetOffset(descriptor, offset + readBytes); return((int)readBytes); }
/// <summary> /// Connection to IP /// </summary> /// <param name="ip">IP</param> /// <param name="port">Port</param> /// <returns></returns> public static unsafe TCPConnection Connect(byte[] ip, ushort port) { ushort inPort = RequestPort(); int startSeq = Random.Rand(); if (!ARP.IpExists(ip)) { byte[] mac = new byte[6]; for (int i = 0; i < 6; i++) { mac[i] = 0xFF; } ARP.ArpSend(ARP.OP_REQUEST, mac, ip); Heap.Free(mac); } while (!ARP.IpExists(ip)) { Tasking.Yield(); } TCPConnection con = new TCPConnection(); con.DestPort = port; con.InPort = inPort; con.State = TCPConnectionState.CLOSED; con.XID = Random.Rand(); con.SequenceNumber = (uint)startSeq; con.NextSequenceNumber = Byte.ReverseBytes(Byte.ReverseBytes(con.SequenceNumber) + 1); con.Type = TCPConnectionType.CONNECTION; con.ReceiveQueue = new Queue(); for (int i = 0; i < 4; i++) { con.IP[i] = ip[i]; } m_connections[inPort] = con; handleConnection(con, null, null, 0); return(con); }
public Logic(TMBot bot) { botName = bot.config.Username; parent = bot; PREFIXPATH = Path.Combine("CS", botName); UNSTICKEREDPATH = Path.Combine(PREFIXPATH, "emptystickered.txt"); __database__ = new SalesDatabase(PREFIXPATH); __emptystickered__ = new EmptyStickeredDatabase(); DATABASEJSONPATH = Path.Combine(PREFIXPATH, "database.json"); BLACKLISTPATH = Path.Combine(PREFIXPATH, "blackList.txt"); MONEYTPATH = Path.Combine(PREFIXPATH, "money.txt"); if (!Directory.Exists(PREFIXPATH)) { Directory.CreateDirectory(PREFIXPATH); } Tasking.Run(StartUp, botName); }
public void Init() { if (Log == null) { Log = new NewMarketLogger(this); } Log.Info("Initializing TMBot " + bot.DisplayName); logic = new Logic(this); protocol = new Protocol(this); logic.Log = Log; protocol.Log = Log; logic.Protocol = protocol; protocol.Logic = logic; WaitingForRestart = false; Tasking.Run(Delayer, botName); }
/// <summary> /// Read from EEP /// </summary> /// <param name="adr">EEP address</param> /// <returns></returns> private unsafe static ushort eepRead(uint adr) { /** * Start read, and write address */ uint *ptr = (uint *)(m_register_base + REG_EERD); *ptr = (REG_EERD_START) | (adr << 8); /** * Wait till done */ while ((*ptr & REG_EERD_DONE) == 0) { Tasking.Yield(); } return((ushort)((*ptr >> 16) & 0xFFFF)); }
private void BackgroundCheck() { Thread.Sleep(60000); while (!disposed) { try { foreach (BotConfig bot in coreConfig.Bots) { if (!PingedRecently(bot.Username)) { logger.Warn($"Бот {bot.Username} давно не пинговал, видимо, он умер."); VK.Alert($"Бот {bot.Username} давно не пинговал, видимо, он умер."); } } } catch { } Tasking.WaitForFalseOrTimeout(() => !disposed, 60000).Wait(); ReloadConfig(); } }
/// <summary> /// Waits for (a) process(es) to exit /// </summary> /// <param name="pid">The PID or other identification</param> /// <param name="status">Pointer to status</param> /// <param name="options">Options</param> /// <returns>The error code</returns> public static unsafe ErrorCode WaitPID(int pid, int *status, int options) { // Wait for specific PID if (pid > 0) { // Don't wait, just check if ((options & WNOHANG) == WNOHANG) { if (Tasking.GetTaskByPID(pid) != null) { return(ErrorCode.SUCCESS); } else { return(ErrorCode.ECHILD); } } // If the task is still found, it means it's still there while (Tasking.GetTaskByPID(pid) != null) { Tasking.Yield(); } } // Wait for any child process whose group ID == calling process group ID else if (pid == 0) { } // Wait for any child process else if (pid == -1) { } // Wait for any child process whose group ID == calling process group ID else if (pid < -1) { } return(ErrorCode.SUCCESS); }
/// <summary> /// Read from fifo /// </summary> /// <param name="buffer">The buffer where to put the data into</param> /// <param name="size">The amount of bytes read</param> /// <param name="offset">The offset in the buffer</param> /// <returns>The amount of read bytes</returns> public unsafe uint Read(byte[] buffer, uint size, uint offset) { uint j = offset; if (m_wait) { while (m_head == m_tail) { Tasking.Yield(); } } for (uint i = 0; i < size; i++) { // Is there data? if (m_tail != m_head) { AvailableBytes--; buffer[j] = m_buffer[m_tail]; j++; m_tail++; // Time to flip the tail? if (m_tail >= m_size) { m_tail = 0; } } else { // We may return if we shouldn't wait return(i); } } return(size); }
/// <summary> /// Kernel entrypoint /// </summary> /// <param name="header">The multiboot header</param> /// <param name="magic">The magic</param> /// <param name="end">The end address of the kernel</param> public static unsafe void KernelMain(Multiboot.Header *header, uint magic, void *end) { heapStart = end; Console.Clear(); X86Arch.EarlyInit(); processMultiboot(header, magic); Heap.InitTempHeap(heapStart); X86Arch.Init(); Random.Init(); VFS.Init(); initPCIDevices(); Keyboard.Init(); Tasking.Init(); BootParams.Init(Util.CharPtrToString((char *)header->CMDLine)); initUSB(); initStorage(); mountBootPartition(); //initNetworking(); initSound(); runUserspace(); // Idle loop while (true) { CPU.HLT(); } }