Kernel - Change virtual memory API to use void* for virtual addresses
[tpg/acess2.git] / KernelLand / Kernel / drv / pty.c
1 /*
2  * Acess2 Kernel
3  * - By John Hodge (thePowersGang)
4  *
5  * drv/pty.c
6  * - Pseudo Terminals
7  */
8 #define DEBUG   0
9 #include <acess.h>
10 #include <vfs.h>
11 #include <fs_devfs.h>
12 #include <drv_pty.h>
13 #include <modules.h>
14 #include <rwlock.h>
15 #include <mutex.h>
16 #include <posix_signals.h>
17
18 // === CONSTANTS ===
19 #define OUTPUT_RINGBUFFER_LEN   1024    // Number of bytes in output queue before client blocks
20 #define INPUT_RINGBUFFER_LEN    256     // Number of bytes in input queue before being dropped
21 #define INPUT_LINE_LEN  256
22
23 // === TYPES ===
24 struct sPTY
25 {
26         tPTY    *Next;
27         
28         char    *Name;
29          int    NumericName;
30         
31         void    *OutputHandle;
32         tPTY_OutputFcn  OutputFcn;
33         tPTY_ReqResize  ReqResize;
34         tPTY_ModeSet    ModeSet;
35
36         struct ptymode  Mode;
37         struct ptydims  Dims;
38
39          int    HasHitEOF;      
40         tMutex  InputMutex;
41          int    InputWritePos;
42          int    InputReadPos;
43         char    InputData[INPUT_RINGBUFFER_LEN];
44         
45          int    LineLength;
46         char    LineData[INPUT_LINE_LEN];
47
48         tMutex  OutputMutex;    
49          int    OutputWritePos;
50          int    OutputReadPos;
51         char    OutputData[OUTPUT_RINGBUFFER_LEN];
52         
53         tVFS_Node       *ServerNode;
54         tVFS_Node       ClientNode;
55         tVFS_ACL        OwnerRW;
56
57         tPGID   ControllingProcGroup;
58 };
59
60 // === PROTOTYPES ===
61  int    PTY_Install(char **Arguments);
62  int    PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
63 tVFS_Node       *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
64
65 size_t  _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len);
66 size_t  _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len);
67 size_t  PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length);
68 size_t  PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length);
69 // PTY_SendInput
70 size_t  PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
71 size_t  PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
72 void    PTY_ReferenceClient(tVFS_Node *Node);
73 void    PTY_CloseClient(tVFS_Node *Node);
74 size_t  PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
75 size_t  PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
76 void    PTY_CloseServer(tVFS_Node *Node);
77  int    PTY_IOCtl(tVFS_Node *Node, int ID, void *Arg);
78
79 // === GLOBALS ===
80 MODULE_DEFINE(0, 0x100, PTY, PTY_Install, NULL, NULL);
81 tVFS_NodeType   gPTY_NodeType_Root = {
82         .TypeName = "PTY-Root",
83         .ReadDir = PTY_ReadDir,
84         .FindDir = PTY_FindDir,
85 };
86 tVFS_NodeType   gPTY_NodeType_Client = {
87         .TypeName = "PTY-Client",
88         .Read = PTY_ReadClient,
89         .Write = PTY_WriteClient,
90         .IOCtl = PTY_IOCtl,
91         .Reference = PTY_ReferenceClient,
92         .Close = PTY_CloseClient
93 };
94 tVFS_NodeType   gPTY_NodeType_Server = {
95         .TypeName = "PTY-Server",
96         .Read = PTY_ReadServer,
97         .Write = PTY_WriteServer,
98         .IOCtl = PTY_IOCtl,
99         .Close = PTY_CloseServer
100 };
101 tDevFS_Driver   gPTY_Driver = {
102         .Name = "pts",
103         .RootNode = {
104                 .Flags = VFS_FFLAG_DIRECTORY,
105                 .Type = &gPTY_NodeType_Root,
106                 .Size = -1
107         }
108 };
109  int    giPTY_NumCount;
110 tRWLock glPTY_NumPTYs;
111 tPTY    *gpPTY_FirstNumPTY;
112  int    giPTY_NamedCount;
113 tRWLock glPTY_NamedPTYs;
114 tPTY    *gpPTY_FirstNamedPTY;
115
116 // === CODE ===
117 int PTY_Install(char **Arguments)
118 {
119         DevFS_AddDevice(&gPTY_Driver);
120         return MODULE_ERR_OK;
121 }
122
123 // --- Management ---
124 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet, const struct ptydims *InitialDims, const struct ptymode *InitialMode)
125 {
126         tPTY    **prev_np = NULL;
127         size_t  namelen;
128          int    idx = 1;
129         
130         if( !Name )
131                 Name = "";
132         
133         if( Name[0] == '\0' )
134         {
135                 RWLock_AcquireWrite(&glPTY_NumPTYs);
136                 // Get a pty ID if Name==NULL
137                 prev_np = &gpPTY_FirstNumPTY;
138                 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
139                 {
140                         if( pty->NumericName > idx )
141                                 break;
142                         idx ++;
143                 }
144                 namelen = snprintf(NULL,0, "%u", idx);
145         }
146         else if( Name[strlen(Name)-1] == '#' )
147         {
148                 // Sequenced PTYs
149                 // - "gui#" would translate to "gui0", "gui1", "gui2", ...
150                 //   whichever is free
151                 prev_np = &gpPTY_FirstNamedPTY;
152
153                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
154                 idx = 0;
155                 namelen = strlen(Name)-1;
156                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
157                 {
158                          int    cmp = strncmp(pty->Name, Name, namelen);
159                         if( cmp < 0 )
160                                 continue ;
161                         if( cmp > 0 )
162                                 break;
163
164                         // Skip non-numbered
165                         if( pty->Name[namelen] == '\0' )
166                                 continue ;                      
167
168                         // Find an unused index
169                         char    *name_end;
170                          int    this_idx = strtol(pty->Name+namelen, &name_end, 10);
171                         if( *name_end != '\0' )
172                                 continue;
173                         if( this_idx > idx )
174                                 break;
175                         idx ++;
176                 }
177                 
178                 namelen += snprintf(NULL, 0, "%u", idx);
179         }
180         else
181         {
182                 prev_np = &gpPTY_FirstNamedPTY;
183                 
184                 // Check the name isn't decimal
185                 char *end;
186                 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
187                         errno = EINVAL;
188                         return NULL;
189                 }
190
191                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
192                 // Detect duplicates
193                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
194                 {
195                          int    cmp = strcmp(pty->Name, Name);
196                         if( cmp < 0 )
197                                 continue;
198                         if( cmp == 0 ) {
199                                 RWLock_Release(&glPTY_NamedPTYs);
200                                 errno = EEXIST;
201                                 return NULL;
202                         }
203                         break;
204                 }
205                 namelen = strlen(Name);
206                 idx = -1;
207         }
208         
209         tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
210         if(!ret) {
211                 errno = ENOMEM;
212                 return NULL;
213         }
214         
215         // - List maintainance
216         ret->Next = *prev_np;
217         *prev_np = ret;
218         // - PTY Name (Used by VT)
219         ret->Name = (char*)(ret + 1);
220         if( idx == -1 )
221                 strcpy(ret->Name, Name);
222         else if( Name[0] )
223                 sprintf(ret->Name, "%.*s%u", strlen(Name)-1, Name, idx);
224         else
225                 sprintf(ret->Name, "%u", idx);
226         ret->NumericName = idx;
227         // - Output function and handle (same again)
228         ret->OutputHandle = Handle;
229         ret->OutputFcn = Output;
230         ret->ReqResize = ReqResize;
231         ret->ModeSet = ModeSet;
232         // - Initialise modes
233         if( InitialDims )
234                 ret->Dims = *InitialDims;
235         if( InitialMode )
236                 ret->Mode = *InitialMode;
237         // - Client node
238         ret->ClientNode.ImplPtr = ret;
239         ret->ClientNode.Type = &gPTY_NodeType_Client;
240         ret->ClientNode.UID = Threads_GetUID();
241         ret->ClientNode.GID = Threads_GetGID();
242         ret->ClientNode.NumACLs = 1;
243         ret->ClientNode.ACLs = &ret->OwnerRW;
244         // - Owner Read-Write ACL
245         ret->OwnerRW.Ent.ID = Threads_GetUID();
246         ret->OwnerRW.Perm.Perms = -1;
247
248         if( Name[0] ) {
249                 giPTY_NamedCount ++;
250                 RWLock_Release(&glPTY_NamedPTYs);
251         }
252         else {
253                 giPTY_NumCount ++;
254                 RWLock_Release(&glPTY_NumPTYs); 
255         }
256
257         return ret;
258 }
259
260 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
261 {
262         if( Mode )
263         {
264                 // (for now) userland terminals can't be put into framebuffer mode
265                 // - Userland PTYs are streams, framebuffer is a block
266                 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
267                         errno = EINVAL;
268                         return -1;
269                 }
270                 if( WasClient )
271                 {
272                         if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
273                         {
274                                 errno = EINVAL;
275                                 return -1;
276                         }
277                         else if( !PTY->OutputFcn )
278                         {
279                                 Log_Warning("PTY", "TODO: Inform server of client SETMODE, halt output");
280                                 // Block slave write until master ACKs
281                                 // 0-length read on master indicates need to GETMODE
282                         }
283                 }
284                 else
285                 {
286                         // Should the client be informed that the server just twiddled the modes?
287                         Log_Warning("PTY", "Server changed mode, TODO: inform client?");
288                 }
289                 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
290                 PTY->Mode = *Mode;
291         }
292         if( Dims )
293         {
294                 if( WasClient )
295                 {
296                         // Poke the server?
297                         if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
298                         {
299                                 errno = EINVAL;
300                                 return -1;
301                         }
302                         else if( !PTY->OutputFcn )
303                         {
304                                 // Inform server process... somehow
305                                 Log_Warning("PTY", "TODO: Inform server of client resize request");
306                         }
307                 }
308                 else
309                 {
310                         // SIGWINSZ to client
311                         Threads_SignalGroup(PTY->ControllingProcGroup, SIGWINCH);
312                 }
313                 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
314                 PTY->Dims = *Dims;
315         }
316         return 0;
317 }
318
319 void PTY_Close(tPTY *PTY)
320 {
321         
322 }
323
324 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
325 {
326         size_t space = (*rd - *wr + buflen - 1) % buflen;
327         len = MIN(space, len);
328         if(*wr + len >= buflen) {
329                 size_t prelen = buflen - *wr;
330                 memcpy((char*)buf + *wr, data, prelen);
331                 memcpy(buf, (char*)data + prelen, len - prelen);
332                 *wr = len - prelen;
333         }
334         else {
335                 memcpy((char*)buf + *wr, data, len);
336                 *wr += len;
337         }
338         return len;
339 }
340 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
341 {
342         size_t space = (*wr - *rd + buflen) % buflen;
343         len = MIN(space, len);
344         if(*rd + len >= buflen) {
345                 size_t prelen = buflen - *rd;
346                 memcpy(data, (char*)buf + *rd, prelen);
347                 memcpy((char*)data + prelen, buf, len - prelen);
348                 *rd = len - prelen;
349         }
350         else {
351                 memcpy(data, (char*)buf + *rd, len);
352                 *rd += len;
353         }
354         return len;
355 }
356
357 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
358 {
359         size_t  ret;
360
361         Mutex_Acquire(&PTY->InputMutex);        
362
363         ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
364                 Input, Length);
365         
366         Mutex_Release(&PTY->InputMutex);
367
368         VFS_MarkAvaliable(&PTY->ClientNode, 1);
369         if(ret < Length && PTY->ServerNode)
370                 VFS_MarkFull(PTY->ServerNode, 1);       
371
372         return ret;
373 }
374
375 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
376 {
377         size_t  ret = 1, print = 1;
378         
379         // Input mode stuff only counts for text output mode
380         // - Any other mode sends Uint32 keypresses
381         if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
382                 return PTY_int_WriteInput(PTY, Input, Length);
383         // If in raw mode, flush directly
384         if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
385                 return PTY_int_WriteInput(PTY, Input, Length);
386         
387         if( PTY->Mode.InputMode & PTYIMODE_CANON )
388         {
389                 
390                 switch(Input[0])
391                 {
392                 case 3: // INTR - ^C
393                         // Send SIGINT
394                         Threads_SignalGroup(PTY->ControllingProcGroup, SIGINT);
395                         print = 0;
396                         break;
397                 case 4: // EOF - ^D
398                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
399                         PTY->HasHitEOF = (PTY->LineLength == 0);
400                         PTY->LineLength = 0;
401                         print = 0;
402                         break;
403                 case 8: // Backspace
404                         if(PTY->LineLength != 0) {
405                                 PTY->LineLength --;
406                                 PTY_WriteClient(&PTY->ClientNode, 0, 3, "\b \b", 0);
407                         }
408                         print = 0;
409                         break;
410                 case 'w'-'a':   // Word erase
411                         while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
412                                 PTY_WriteClient(&PTY->ClientNode, 0, 1, "\b", 0);
413                         PTY_WriteClient(&PTY->ClientNode, 0, 3, "\x1b[K", 0);
414                         print = 0;
415                         break;
416                 case 'u'-'a':   // Kill
417                         PTY_WriteClient(&PTY->ClientNode, 0, 8, "\x1b[2K\x1b[0G", 0);
418                         PTY->LineLength = 0;
419                         print = 0;
420                         break;
421                 case 'v'-'a':
422                         Input ++;
423                         Length --;
424                         ret ++;
425                         goto _default;
426                 case '\0':
427                 case '\n':
428                         if(PTY->LineLength == INPUT_LINE_LEN) {
429                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
430                                 PTY->LineLength = 0;
431                         }
432                         PTY->LineData[PTY->LineLength++] = '\n';
433                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
434                         PTY->LineLength = 0;
435                         break;
436                 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
437                 //case 0x1B:
438                 //      break;
439                 default:
440                 _default:
441                         if(PTY->LineLength == INPUT_LINE_LEN) {
442                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
443                                 PTY->LineLength = 0;
444                         }
445                         PTY->LineData[PTY->LineLength++] = Input[0];
446                         break;
447                 }
448         }
449         else
450         {
451                 #if 0
452                 if( PTY->Mode.InputMode & PTYIMODE_NLCR )
453                 {
454                         if( Input[0] == '\n' ) {
455                                 char ch = '\r';
456                                 ret = PTY_int_WriteInput(PTY, &ch, 1);
457                         }
458                         else {
459                                  int    i;
460                                 for( i = 0; i < Length && Input[i] != '\n'; i ++ )
461                                         ;
462                                 ret = PTY_int_WriteInput(PTY, Input, i);
463                         }
464                 }
465                 // TODO: CRNL mode?
466                 else
467                 #endif
468                         ret = PTY_int_WriteInput(PTY, Input, Length);
469         }
470         
471         // Echo if requested
472         if( PTY->Mode.InputMode & PTYIMODE_ECHO )
473         {
474                 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
475         }
476         
477         return ret;
478 }
479
480 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
481 {
482         size_t ret = 0;
483         while( ret < Length && !PTY->ClientNode.BufferFull )
484         {
485                 // TODO: Detect blocking?
486                 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
487         }
488         return ret;
489 }
490
491 // --- VFS ---
492 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
493 {
494         tPTY    *pty = NULL;
495          int    idx = Pos;
496         if( idx < giPTY_NumCount )
497         {
498                 RWLock_AcquireRead(&glPTY_NumPTYs);
499                 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
500                         idx --;
501                 RWLock_Release(&glPTY_NumPTYs);
502         }
503         else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
504         {
505                 idx -= giPTY_NumCount;
506                 RWLock_AcquireRead(&glPTY_NamedPTYs);
507                 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
508                         idx --;
509                 RWLock_Release(&glPTY_NamedPTYs);
510         }
511
512         if( !pty ) {
513                 return -1;
514         }
515
516         strncpy(Name, pty->Name, FILENAME_MAX);
517         return 0;
518 }
519
520 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
521 {
522         char    *end;
523          int    num = strtol(Name, &end, 10);
524
525         if( strcmp(Name, "ptmx") == 0 ) {
526                 tVFS_Node       *ret = calloc(sizeof(tVFS_Node), 1);
527                 ret->Size = -1;
528                 ret->Type = &gPTY_NodeType_Server;
529                 return ret;
530         } 
531         
532         if( Name[0] == '\0' )
533                 return NULL;
534         
535         tPTY    *ret = NULL;
536         if( num && end[0] == '\0' )
537         {
538                 // Numeric name
539                 RWLock_AcquireRead(&glPTY_NumPTYs);
540                 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
541                 {
542                         if( pty->NumericName > num )
543                                 break;
544                         if( pty->NumericName == num ) {
545                                 ret = pty;
546                                 break;
547                         }
548                 }
549                 RWLock_Release(&glPTY_NumPTYs);
550         }
551         else
552         {
553                 // String name
554                 RWLock_AcquireRead(&glPTY_NamedPTYs);
555                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
556                 {
557                         int cmp = strcmp(pty->Name, Name);
558                         if(cmp > 0)
559                                 break;
560                         if(cmp == 0 ) {
561                                 ret = pty;
562                                 break;
563                         }
564                 }
565                 RWLock_Release(&glPTY_NamedPTYs);
566         }
567 //      Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
568         if( ret ) {
569                 tVFS_Node       *retnode = &ret->ClientNode;
570                 retnode->ReferenceCount ++;
571                 return retnode;
572         }
573         else
574                 return NULL;
575 }
576
577 //\! Read from the client's input
578 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
579 {
580         tPTY *pty = Node->ImplPtr;
581         
582         // Read from flushed queue
583         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
584          int    rv;
585 _select:
586         // If server has disconnected, return EIO
587         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
588                 //Threads_PostSignal(SIGPIPE);
589                 errno = EIO;
590                 return -1;
591         }
592         // Wait for data to be ready
593         rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
594         if(!rv) {
595                 errno = (timeout ? EWOULDBLOCK : EINTR);
596                 return -1;
597         }
598
599         Mutex_Acquire(&pty->InputMutex);
600         Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
601                 Buffer, Length);
602         if( Length && pty->ServerNode )
603                 VFS_MarkFull(pty->ServerNode, 0);
604         Mutex_Release(&pty->InputMutex);
605
606         if(pty->InputReadPos == pty->InputWritePos)
607                 VFS_MarkAvaliable(Node, 0);
608
609         if(Length == 0 && !pty->HasHitEOF) {
610                 goto _select;
611         }
612         pty->HasHitEOF = 0;
613
614         return Length;
615 }
616
617 //\! Write to the client's output
618 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
619 {
620         tPTY *pty = Node->ImplPtr;
621
622         // If the server has terminated, send SIGPIPE
623         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
624         {
625                 Threads_PostSignal(SIGPIPE);
626                 errno = EIO;
627                 return -1;
628         }       
629
630         // Write to either FIFO or directly to output function
631         if( pty->OutputFcn ) {
632                 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
633                 return Length;
634         }
635         
636         // FIFO
637         size_t remaining = Length;
638         do
639         {
640                 tTime   timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
641                  int    rv;
642                 
643                 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
644                 if(!rv) {
645                         errno = (timeout ? EWOULDBLOCK : EINTR);
646                         return -1;
647                 }
648                 
649                 // Write to output ringbuffer
650                 size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
651                         &pty->OutputReadPos, &pty->OutputWritePos,
652                         Buffer, remaining);
653                 LOG("Wrote %i of %i : '%.*s'", written, remaining, written, Buffer);
654                 VFS_MarkAvaliable(pty->ServerNode, 1);
655                 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
656                         VFS_MarkFull(Node, 1);
657                 
658                 remaining -= written;
659                 Buffer = (const char*)Buffer + written;
660         } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
661         
662         return Length - remaining;
663 }
664
665 void PTY_ReferenceClient(tVFS_Node *Node)
666 {
667         Node->ReferenceCount ++;
668 }
669
670 void PTY_CloseClient(tVFS_Node *Node)
671 {
672         tPTY    *pty = Node->ImplPtr;
673         Node->ReferenceCount --;
674
675         // Remove PID from list
676         // TODO: Maintain list of client processes
677
678         // Free structure if this was the last open handle
679         if( Node->ReferenceCount > 0 )
680                 return ;
681         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
682         {
683                 // Free the structure! (Should be off the PTY list now)
684                 free(pty->ServerNode);
685                 free(pty);
686         }
687 }
688
689 //\! Read from the client's output
690 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
691 {
692         tPTY *pty = Node->ImplPtr;
693         if( !pty ) {
694                 errno = EIO;
695                 return -1;
696         }
697
698         // TODO: Prevent two servers fighting over client's output      
699         if( pty->OutputFcn )
700         {
701                 // Kernel-land PTYs can't be read from userland
702                 return 0;
703         }
704         
705         // Read back from fifo
706         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
707         int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
708         if(!rv) {
709                 errno = (timeout ? EWOULDBLOCK : EINTR);
710                 return -1;
711         }
712         
713         Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
714                 &pty->OutputReadPos, &pty->OutputWritePos,
715                 Buffer, Length);
716         LOG("Read %i '%.*s'", Length, Length, Buffer);
717         if( pty->OutputReadPos == pty->OutputWritePos )
718                 VFS_MarkAvaliable(Node, 0);
719         VFS_MarkFull(&pty->ClientNode, 0);
720         
721         return Length;
722 }
723
724 //\! Write to the client's input
725 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
726 {
727         tPTY    *pty = Node->ImplPtr;
728         if( !pty ) {
729                 errno = EIO;
730                 return -1;
731         }
732
733         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
734         int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
735         if(!rv) {
736                 errno = (timeout ? EWOULDBLOCK : EINTR);
737                 return -1;
738         }
739         size_t  used = 0;
740         do {
741                 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
742         } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
743         
744         if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
745                 VFS_MarkFull(Node, 1);
746         return used;
747 }
748
749 void PTY_CloseServer(tVFS_Node *Node)
750 {
751         tPTY    *pty = Node->ImplPtr;
752         // Dereference node
753         Node->ReferenceCount --;
754         // If reference count == 0, remove from main list
755         if( Node->ReferenceCount > 0 )
756                 return ;
757         
758         // Locate on list and remove
759         tPTY    **prev_np;
760         if( pty->NumericName == -1 ) {
761                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
762                 prev_np = &gpPTY_FirstNamedPTY;
763         }
764         else {
765                 RWLock_AcquireWrite(&glPTY_NumPTYs);
766                 prev_np = &gpPTY_FirstNumPTY;
767         }
768
769         // Search list until *prev_np is equal to pty   
770         for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
771                 ;
772         
773         // Remove
774         if( *prev_np != pty ) {
775                 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
776         }
777         else {
778                 *prev_np = pty->Next;
779         }
780         
781         // Clean up lock
782         if( pty->NumericName == -1 ) {
783                 RWLock_Release(&glPTY_NamedPTYs);
784                 giPTY_NamedCount --;
785         }
786         else {
787                 RWLock_Release(&glPTY_NumPTYs);
788                 giPTY_NumCount --;
789         }
790
791         // Send SIGHUP to controling PGID
792         if( pty->ControllingProcGroup > 0 ) {
793                 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
794         }
795
796         // If there are no open children, we can safely free this PTY
797         if( pty->ClientNode.ReferenceCount == 0 ) {
798                 free(Node);
799                 free(pty);
800         }
801 }
802
803 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
804 {
805         tPTY    *pty = Node->ImplPtr;
806         struct ptymode  *mode = Data;
807         struct ptydims  *dims = Data;
808         
809         int     is_server = !pty || Node == pty->ServerNode;
810
811         switch(ID)
812         {
813         case DRV_IOCTL_TYPE:    return DRV_TYPE_TERMINAL;
814         case DRV_IOCTL_IDENT:   memcpy(Data, "PTY\0", 4);       return 0;
815         case DRV_IOCTL_VERSION: return 0x100;
816         case DRV_IOCTL_LOOKUP:  return 0;
817         
818         case PTY_IOCTL_GETMODE:
819                 if( !pty )      return 0;
820                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
821                 *mode = pty->Mode;
822                 // TODO: ACK client's SETMODE
823                 return 0;
824         case PTY_IOCTL_SETMODE:
825                 if( !pty )      return 0;
826                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
827                 PTY_SetAttrib(pty, NULL, mode, !is_server);
828                 return 0;
829         case PTY_IOCTL_GETDIMS:
830                 if( !pty )      return 0;
831                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
832                 *dims = pty->Dims;
833                 return 0;
834         case PTY_IOCTL_SETDIMS:
835                 if( !pty )      return 0;
836                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
837                 PTY_SetAttrib(pty, dims, NULL, !is_server);
838                 return 0;
839         case PTY_IOCTL_GETID:
840                 if( pty )
841                 {
842                         size_t  len = strlen(pty->Name)+1;
843                         if( Data )
844                         {
845                                 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
846                                 strcpy(Data, pty->Name);
847                         }
848                         return len;
849                 }
850                 return 0;
851         case PTY_IOCTL_SETID:
852                 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
853                 if( pty )       return EALREADY;
854                 pty = PTY_Create(Data, NULL, NULL,NULL, NULL, NULL,NULL);
855                 if(pty == NULL)
856                         return 1;
857                 Node->ImplPtr = pty;
858                 pty->ServerNode = Node;
859                 return 0;
860         case PTY_IOCTL_SETPGRP:
861                 // TODO: Should this only be done by client?
862                 if( Data )
863                 {
864                         if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
865                         pty->ControllingProcGroup = *(tPGID*)Data;
866                         Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
867                 }
868                 return pty->ControllingProcGroup;
869         }
870         errno = ENOSYS;
871         return -1;
872 }
873

UCC git Repository :: git.ucc.asn.au