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

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