repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
frankjas/libjr
libjr/htable/htablpfx.c
<reponame>frankjas/libjr #include "project.h" void jr_HTableSetContainers ( jr_HTable * htable, ...) { va_list arg_list; va_start (arg_list, htable); jr_HTableSetContainersFromVA_List (htable, arg_list); va_end (arg_list); } void jr_HTableSetContainersFromVA_List (htable, arg_list) jr_HTable * htable; va_list arg_list; { jr_PrefixInfoType * prefix_array; jr_int prefix_size; jr_int needs_transform_fn = 1; prefix_array = jr_PrefixArrayCreateFromVA_List (arg_list, needs_transform_fn); prefix_size = jr_PrefixArrayInitPrefixes (prefix_array); if (htable) { jr_HTableSetPrefixSize (htable, prefix_size, jr_PrefixArrayTransformElement, prefix_array); } }
frankjas/libjr
libjr/syscalls/username.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <unistd.h> #include <string.h> #include <pwd.h> #include <grp.h> #include <errno.h> #include "jr/syscalls.h" #include "jr/error.h" /* ** 11/16/05: Could also use the environment USER and HOME to get the current user and dir. ** Under Microsoft, USERNAME and HOMEPATH. */ jr_int jr_GetUserName (namebuf, buf_length, error_buf) char * namebuf ; jr_int buf_length; char * error_buf; { jr_int uid = getuid() ; struct passwd * passwd_ptr ; passwd_ptr = getpwuid(uid) ; if (passwd_ptr == 0) { jr_esprintf (error_buf, "couldn't get password entry: %s", strerror (errno)); return jr_ConvertErrno (errno); } if ((jr_int) strlen (passwd_ptr->pw_name) + 1 > buf_length) { jr_esprintf (error_buf, "buffer too small"); return jr_NO_ROOM_ERROR; } sprintf (namebuf, "%.*s", buf_length - 1, passwd_ptr->pw_name); return 0; } jr_int jr_GetUserHomeDir (path_buf, buf_length, error_buf) char * path_buf ; jr_int buf_length; char * error_buf; { jr_int uid = getuid() ; struct passwd * passwd_ptr ; passwd_ptr = getpwuid(uid) ; if (passwd_ptr == 0) { jr_esprintf (error_buf, "couldn't get password entry: %s", strerror (errno)); return jr_ConvertErrno (errno); } if ((jr_int) strlen (passwd_ptr->pw_dir) + 1 > buf_length) { jr_esprintf (error_buf, "buffer too small"); return jr_NO_ROOM_ERROR; } sprintf (path_buf, "%.*s", buf_length - 1, passwd_ptr->pw_dir); return 0; } jr_int jr_GetGroupName (namebuf, buf_length, error_buf) char * namebuf ; jr_int buf_length; char * error_buf; { jr_int gid = getgid() ; struct group * group_ptr ; group_ptr = getgrgid(gid) ; if (group_ptr == 0) { jr_esprintf (error_buf, "couldn't get password entry: %s", strerror (errno)); return jr_ConvertErrno (errno); } if ((jr_int) strlen (group_ptr->gr_name) + 1 > buf_length) { jr_esprintf (error_buf, "buffer too small"); return jr_NO_ROOM_ERROR; } sprintf (namebuf, "%.*s", buf_length - 1, group_ptr->gr_name); return 0; } jr_int jr_IsRootUser () { jr_int uid = getuid() ; if (uid == 0) { return 1; } return 0; }
frankjas/libjr
libjr/llist/llistadd.c
<filename>libjr/llist/llistadd.c #include "project.h" void *jr_LListAppendElement (list, prev, new) jr_LList * list; void * prev; void * new; { if (prev == 0) { /* do an add to head */ jr_LListNextElementPtr (list, new) = jr_LListHeadPtr(list); jr_LListHeadPtr(list) = new; } else { jr_LListNextElementPtr (list, new) = jr_LListNextElementPtr (list, prev); jr_LListNextElementPtr (list, prev) = new; } if (prev == jr_LListTailPtr(list)) { /* * prev is the current tail * prev could be 0 */ jr_LListTailPtr(list) = new; } return (new); } void *jr_LListExtractNextElement (list, prev) jr_LList * list; void * prev; { void * deleted_element; if (prev == 0) { /* * do a delete from the head */ deleted_element = jr_LListHeadPtr (list); if (deleted_element == 0) { return 0; } jr_LListHeadPtr (list) = jr_LListNextElementPtr (list, deleted_element); } else { deleted_element = jr_LListNextElementPtr (list, prev); if (deleted_element == 0) { /* * prev was the tail, no deleted_element element to delete * return 0 to show that no delete was possible */ return 0; } jr_LListNextElementPtr (list, prev) = jr_LListNextElementPtr ( list, deleted_element ); } if (deleted_element == jr_LListTailPtr(list)) { jr_LListTailPtr (list) = prev; } jr_LListMakeNullElement (list, deleted_element); /* * so prefix transformations on this element don't affect anything */ return deleted_element; } void jr_LListDeleteNextElement (list, prev) jr_LList * list; void * prev; { void * el; el = jr_LListExtractNextElement (list, prev); if (jr_LListAllocatesElements (list)) { jr_LListFreeElement (list, el); } }
frankjas/libjr
include/jr/epoll.h
#ifndef _JR_EPOLL_H___ #define _JR_EPOLL_H___ #include "ezport.h" #ifndef missing_epoll_h #include <sys/epoll.h> #endif /******** epoll helper functions ********/ extern void jr_epoll_event_init_ptr ( struct epoll_event * event_info, jr_int event_flags, void * ptr); #define jr_epoll_event_ptr(event_info) \ ((event_info)->data.ptr) #define jr_epoll_event_has_read(event_info) \ ((event_info)->events & EPOLLIN) #define jr_epoll_event_has_write(event_info) \ ((event_info)->events & EPOLLOUT) /******** epoll replacement ********/ #ifdef missing_epoll_in_kernel extern jr_int jr_epoll_close ( jr_int epoll_fd); extern jr_int jr_epoll_create ( jr_int estimated_num_clients); extern jr_int jr_epoll_ctl ( jr_int epoll_fd, jr_int epoll_op, jr_int io_fd, struct epoll_event * event_info); extern jr_int jr_epoll_wait ( jr_int epoll_fd, struct epoll_event * event_array, jr_int max_events, jr_int timeout_seconds); #else #define jr_epoll_create(num_clnts) epoll_create (num_clnts) #define jr_epoll_ctl(efd, eop, ifd, eptr) epoll_ctl (efd, eop, ifd, eptr) #define jr_epoll_wait(efd, ea, me, ts) epoll_wait (efd, ea, me, ts) #define jr_epoll_close(epoll_fd) close (epoll_fd) #endif #endif
frankjas/libjr
include/jr/tar.h
#ifndef __TAR_H__ #define __TAR_H__ #include "ezport.h" #include <stdio.h> /* * 6/16/2004: existing tar formats include (from GNU tar info files, "% info tar") * v7 - Unix V7 format * gnu * posix 'ustar' (1988) * posix (2001) */ #define jr_TAR_INTERNAL_ERROR -1 #define jr_TAR_EOF_ERROR -2 #define jr_TAR_BLOCK_SIZE 512 #define jr_TAR_BLOCK_SIZE_NUM_BITS 9 #define jr_TAR_PATH_MAX 255 #define jr_TAR_SYM_LINK_MAX 100 #define jr_TAR_UNAME_MAX 31 #define jr_TAR_GNAME_MAX 31 #define jr_TAR_UID_MAX jr_TAR_MAX_7_BYTE_ASCII_OCTAL #define jr_TAR_GID_MAX jr_TAR_MAX_7_BYTE_ASCII_OCTAL #define jr_TAR_MAX_7_BYTE_ASCII_OCTAL 07777777 /* 2079151 */ #define jr_TAR_MAX_12_BYTE_ASCII_OCTAL jr_UINT_MAX typedef struct { char name [100] ; /* NUL-terminated if NUL fits */ char mode [8] ; /* NUL-terminated digit string (MKS documentation) */ char uid [8] ; /* NUL-terminated digit string (MKS documentation) */ char gid [8] ; /* NUL-terminated digit string (MKS documentation) */ char size [12] ; char mtime [12] ; char chksum [8] ; /* NUL-terminated digit string (MKS documentation) */ char typeflag [1] ; /* see below */ char linkname [100] ; /* NUL-terminated if NUL fits */ char magic [6] ; /* must be TMAGIC (NUL term.) */ char version [2] ; /* must be TVERSION */ char uname [32] ; /* NUL-terminated */ char gname [32] ; /* NUL-terminated */ char devmajor [8] ; /* NUL-terminated digit string (MKS documentation) */ char devminor [8] ; /* NUL-terminated digit string (MKS documentation) */ char prefix [155] ; /* NUL-terminated if NUL fits */ } jr_TarHeaderStruct ; #ifdef missing_tar_h #define TMAGIC "ustar" /* ustar and a null */ #define TMAGLEN 6 #define TVERSION "00" /* 00 and no null */ #define TVERSLEN 2 /* Values used in typeflag field */ #define REGTYPE '0' /* regular file */ #define AREGTYPE '\0' /* regular file */ #define LNKTYPE '1' /* hard link */ #define SYMTYPE '2' /* sym link */ #define CHRTYPE '3' /* character special */ #define BLKTYPE '4' /* block special */ #define DIRTYPE '5' /* directory */ #define FIFOTYPE '6' /* FIFO special */ #define CONTTYPE '7' /* reserved */ /* Bits used in the mode field - values in octal */ #define TSUID 04000 /* set UID on execution */ #define TSGID 02000 /* set GID on execution */ #define TSVTX 01000 /* reserved */ #define TUREAD 00400 /* read by owner */ #define TUWRITE 00200 /* write by owner */ #define TUEXEC 00100 /* execute/search by owner */ #define TGREAD 00040 /* read by group */ #define TGWRITE 00020 /* write by group */ #define TGEXEC 00010 /* execute/search by group */ #define TOREAD 00004 /* read by other */ #define TOWRITE 00002 /* write by other */ #define TOEXEC 00001 /* execute/search by other */ #else # include <tar.h> #endif #define jr_MAJOR_DEV(x) ((jr_int)(((unsigned)(x)>>8)&0377)) #define jr_MINOR_DEV(x) ((jr_int)((x)&0377)) /* * For extracting major and minor numbers from a short. */ /* * 6/15/2004: from <tar.h> * The values for "typeflag": Values 'A'-'Z' are reserved for custom implementations. * All other values are reserved for future POSIX.1 revisions. * * 9/18/2002 These GNU type values are from the GNU/Linux 'tar' source header file tar.h */ #define jr_TAR_GNUTYPE_DUMPDIR 'D' /* This is a dir entry that contains the names */ /* of files that were in the dir at the time the */ /* dump was made. */ #define jr_TAR_GNUTYPE_LONGLINK 'K' /* Identifies the *next* file on the tape as */ /* having a long linkname. */ #define jr_TAR_GNUTYPE_LONGNAME 'L' /* Identifies the *next* file on the tape as */ /* having a long name. */ #define jr_TAR_GNUTYPE_MULTIVOL 'M' /* This is the continuation of a file that began */ /* on another volume. */ #define jr_TAR_GNUTYPE_NAMES 'N' /* For storing filenames that do not fit into */ /* the main header. */ #define jr_TAR_GNUTYPE_SPARSE 'S' /* This is for sparse files. */ #define jr_TAR_GNUTYPE_VOLHDR 'V' /* This file is a tape/volume header. */ /* Ignore it on extraction. */ typedef struct { jr_TarHeaderStruct tar_header[1]; unsigned jr_int mode_int ; unsigned jr_int uid_int ; unsigned jr_int gid_int ; unsigned jr_int size_int ; unsigned jr_int mtime_int ; unsigned jr_int chksum_int ; unsigned jr_int dev_major_int ; unsigned jr_int dev_minor_int ; unsigned jr_int header_offset ; unsigned jr_int data_offset ; unsigned jr_int num_blocks ; } jr_TarEntryType ; extern jr_int jr_TarEntryInitFromRfp PROTO (( jr_TarEntryType * tar_entry_ptr, FILE * rfp, char * error_buf )); extern jr_int jr_TarEntryInitFromFifoRfp PROTO (( jr_TarEntryType * tar_entry_ptr, FILE * rfp, char * error_buf )); extern jr_int jr_TarEntryReadData PROTO (( jr_TarEntryType * tar_entry_ptr, FILE * rfp, void ** opt_data_ref, char * error_buf )); extern jr_int jr_TarEntryCopyData PROTO (( jr_TarEntryType * tar_entry_ptr, FILE * rfp, FILE * wfp, char * error_buf )); extern jr_int jr_TarEntryWriteSegment PROTO (( jr_TarEntryType * tar_entry_ptr, unsigned jr_int total_data_size, const void * opt_data_ptr, FILE * opt_data_rfp, unsigned jr_int curr_data_size, FILE * wfp, char * error_buf )); #define jr_TarEntryWrite( \ tar_entry_ptr, \ total_data_size, opt_data_ptr, opt_data_rfp, \ wfp, error_buf \ ) \ jr_TarEntryWriteSegment ( \ tar_entry_ptr, \ total_data_size, opt_data_ptr, opt_data_rfp, total_data_size, \ wfp, error_buf \ ) extern jr_int jr_TarFileWriteEOF PROTO (( FILE * wfp, char * error_buf )); extern void jr_TarEntrySetIsDir PROTO (( jr_TarEntryType * tar_entry_ptr )); extern void jr_TarEntrySetIsFile PROTO (( jr_TarEntryType * tar_entry_ptr )); extern void jr_TarEntrySetCustomType PROTO (( jr_TarEntryType * tar_entry_ptr, jr_int type_value )); extern void jr_TarEntrySetIsSymLink PROTO (( jr_TarEntryType * tar_entry_ptr, const char * link_name )); extern void jr_TarEntrySetUserInfo PROTO (( jr_TarEntryType * tar_entry_ptr, jr_int uid, const char * opt_uname, jr_int gid, const char * opt_gname )); extern void jr_TarEntrySetPathInfo PROTO (( jr_TarEntryType * tar_entry_ptr, const char * pathname, jr_int is_dir, jr_int mode, jr_int mtime )); extern void jr_TarEntryInit PROTO (( jr_TarEntryType * tar_entry_ptr )); extern void jr_TarEntryUndo PROTO (( jr_TarEntryType * tar_entry_ptr )); extern void jr_TarEntrySetMode PROTO (( jr_TarEntryType * tar_entry_ptr, jr_int mode_int )); extern void jr_TarEntrySetUID PROTO (( jr_TarEntryType * tar_entry_ptr, jr_int uid_int )); extern void jr_TarEntrySetGID PROTO (( jr_TarEntryType * tar_entry_ptr, jr_int gid_int )); extern void jr_TarEntrySetMTime PROTO (( jr_TarEntryType * tar_entry_ptr, jr_int mtime_int )); extern void jr_TarEntrySetSize PROTO (( jr_TarEntryType * tar_entry_ptr, unsigned jr_int size_int )); extern void jr_TarEntrySetDevMajor PROTO (( jr_TarEntryType * tar_entry_ptr, jr_int dev_major )); extern void jr_TarEntrySetDevMinor PROTO (( jr_TarEntryType * tar_entry_ptr, jr_int dev_minor )); extern void jr_TarEntrySetMagic PROTO (( jr_TarEntryType * tar_entry_ptr, const char * magic_string )); extern void jr_TarEntrySetVersion PROTO (( jr_TarEntryType * tar_entry_ptr, const char * magic_string )); extern void jr_TarEntryInitCheckSum PROTO (( jr_TarEntryType * tar_entry_ptr )); extern void jr_TarEntryMakePosixConformant PROTO (( jr_TarEntryType * tar_entry_ptr )); extern const char * jr_TarEntryMakeFullPath PROTO (( jr_TarEntryType * tar_entry_ptr )); extern void jr_TarFilePtrAlign PROTO (( FILE * fp )); extern jr_int jr_TarFilePtrAlignFifoRead PROTO (( FILE * rfp, unsigned jr_int num_bytes_moved )); extern jr_int jr_TarFilePtrAlignFifoWrite PROTO (( FILE * wfp, unsigned jr_int num_bytes_moved )); #define jr_TarEntryHeaderPtr(tar_entry_ptr) ((tar_entry_ptr)->tar_header) #define jr_TarEntryMode(tar_entry_ptr) ((tar_entry_ptr)->mode_int) #define jr_TarEntrySetModeInt(tar_entry_ptr, v) ((tar_entry_ptr)->mode_int = (v)) #define jr_TarEntryUID(tar_entry_ptr) ((tar_entry_ptr)->uid_int) #define jr_TarEntrySetUIDInt(tar_entry_ptr, v) ((tar_entry_ptr)->uid_int = (v)) #define jr_TarEntryGID(tar_entry_ptr) ((tar_entry_ptr)->gid_int) #define jr_TarEntrySetGIDInt(tar_entry_ptr, v) ((tar_entry_ptr)->gid_int = (v)) #define jr_TarEntrySize(tar_entry_ptr) ((tar_entry_ptr)->size_int) #define jr_TarEntrySetSizeInt(tar_entry_ptr, v) ((tar_entry_ptr)->size_int = (v)) #define jr_TarEntryMTime(tar_entry_ptr) ((tar_entry_ptr)->mtime_int) #define jr_TarEntrySetMTimeInt(tar_entry_ptr, v) ((tar_entry_ptr)->mtime_int = (v)) #define jr_TarEntryChkSum(tar_entry_ptr) ((tar_entry_ptr)->chksum_int) #define jr_TarEntrySetChkSumInt(tar_entry_ptr, v) ((tar_entry_ptr)->chksum_int = (v)) #define jr_TarEntryHeaderOffset(tar_entry_ptr) ((tar_entry_ptr)->header_offset) #define jr_TarEntrySetHeaderOffset(tar_entry_ptr, v) ((tar_entry_ptr)->header_offset = (v)) #define jr_TarEntryDataOffset(tar_entry_ptr) ((tar_entry_ptr)->data_offset) #define jr_TarEntrySetDataOffset(tar_entry_ptr, v) ((tar_entry_ptr)->data_offset = (v)) #define jr_TarEntryNumBlocks(tar_entry_ptr) ((tar_entry_ptr)->num_blocks) #define jr_TarEntrySetNumBlocks(tar_entry_ptr, v) ((tar_entry_ptr)->num_blocks = (v)) #define jr_TarEntryDevMajor(tar_entry_ptr) ((tar_entry_ptr)->dev_major_int) #define jr_TarEntrySetDevMajorInt(tar_entry_ptr, v) ((tar_entry_ptr)->dev_major_int = (v)) #define jr_TarEntryDevMinor(tar_entry_ptr) ((tar_entry_ptr)->dev_minor_int) #define jr_TarEntrySetDevMinorInt(tar_entry_ptr, v) ((tar_entry_ptr)->dev_minor_int = (v)) #define jr_TarEntryName(tar_entry_ptr) \ jr_TarHeaderName (jr_TarEntryHeaderPtr (tar_entry_ptr)) #define jr_TarEntryTypeFlag(tar_entry_ptr) \ jr_TarHeaderTypeFlag (jr_TarEntryHeaderPtr (tar_entry_ptr)) #define jr_TarEntrySetTypeFlag(tar_entry_ptr, v) \ jr_TarHeaderSetTypeFlag (jr_TarEntryHeaderPtr (tar_entry_ptr), v) #define jr_TarEntryMagic(tar_entry_ptr) \ jr_TarHeaderMagic (jr_TarEntryHeaderPtr (tar_entry_ptr)) #define jr_TarEntryLinkName(tar_entry_ptr) \ jr_TarHeaderLinkName (jr_TarEntryHeaderPtr (tar_entry_ptr)) #define jr_TarEntryUName(tar_entry_ptr) \ jr_TarHeaderUName (jr_TarEntryHeaderPtr (tar_entry_ptr)) #define jr_TarEntryGName(tar_entry_ptr) \ jr_TarHeaderGName (jr_TarEntryHeaderPtr (tar_entry_ptr)) #define jr_TarEntryPrefix(tar_entry_ptr) \ jr_TarHeaderPrefix (jr_TarEntryHeaderPtr (tar_entry_ptr)) #define jr_TarEntryIsDir(tar_entry_ptr) \ jr_TarHeaderIsDir (jr_TarEntryHeaderPtr (tar_entry_ptr)) #define jr_TarEntryHeaderName(tar_entry_ptr) jr_TarHeaderName ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderMode(tar_entry_ptr) jr_TarHeaderMode ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderUID(tar_entry_ptr) jr_TarHeaderUID ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderGID(tar_entry_ptr) jr_TarHeaderGID ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderSize(tar_entry_ptr) jr_TarHeaderSize ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderMTime(tar_entry_ptr) jr_TarHeaderMTime ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderChkSum(tar_entry_ptr) jr_TarHeaderChkSum ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderTypeFlag(tar_entry_ptr) jr_TarHeaderTypeFlag ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderLinkName(tar_entry_ptr) jr_TarHeaderLinkName ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderMagic(tar_entry_ptr) jr_TarHeaderMagic ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderVersion(tar_entry_ptr) jr_TarHeaderVersion ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderUName(tar_entry_ptr) jr_TarHeaderUName ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderGName(tar_entry_ptr) jr_TarHeaderGName ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderDevMajor(tar_entry_ptr) jr_TarHeaderDevMajor ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderDevMinor(tar_entry_ptr) jr_TarHeaderDevMinor ((tar_entry_ptr)->tar_header) #define jr_TarEntryHeaderPrefix(tar_entry_ptr) jr_TarHeaderPrefix ((tar_entry_ptr)->tar_header) #define jr_TarHeaderName(tar_header_ptr) ((tar_header_ptr)->name) #define jr_TarHeaderMode(tar_header_ptr) ((tar_header_ptr)->mode) #define jr_TarHeaderUID(tar_header_ptr) ((tar_header_ptr)->uid) #define jr_TarHeaderGID(tar_header_ptr) ((tar_header_ptr)->gid) #define jr_TarHeaderSize(tar_header_ptr) ((tar_header_ptr)->size) #define jr_TarHeaderMTime(tar_header_ptr) ((tar_header_ptr)->mtime) #define jr_TarHeaderChkSum(tar_header_ptr) ((tar_header_ptr)->chksum) #define jr_TarHeaderTypeFlag(tar_header_ptr) ((tar_header_ptr)->typeflag[0]) #define jr_TarHeaderLinkName(tar_header_ptr) ((tar_header_ptr)->linkname) #define jr_TarHeaderMagic(tar_header_ptr) ((tar_header_ptr)->magic) #define jr_TarHeaderVersion(tar_header_ptr) ((tar_header_ptr)->version) #define jr_TarHeaderUName(tar_header_ptr) ((tar_header_ptr)->uname) #define jr_TarHeaderGName(tar_header_ptr) ((tar_header_ptr)->gname) #define jr_TarHeaderDevMajor(tar_header_ptr) ((tar_header_ptr)->devmajor) #define jr_TarHeaderDevMinor(tar_header_ptr) ((tar_header_ptr)->devminor) #define jr_TarHeaderPrefix(tar_header_ptr) ((tar_header_ptr)->prefix) #define jr_TarHeaderIsDir(tar_header_ptr) \ (jr_TarHeaderTypeFlag (tar_header_ptr) == DIRTYPE) #define jr_TarHeaderSetTypeFlag(tar_header_ptr, v) ((tar_header_ptr)->typeflag[0] = (v)) extern const char * jr_TarTypeFlagToString PROTO (( jr_int type_flag )); extern unsigned jr_int jr_TarModeToPerms ( jr_int tar_mode); #endif
frankjas/libjr
include/jr/heap.h
#ifndef _heaph #include "ezport.h" #include "jr/alist.h" extern void jr_HeapInsert PROTO((jr_AList *heap, void *obj, jr_int (*cmpfn)())); extern void jr_HeapDeleteMin PROTO((jr_AList *heap, void *obj, jr_int (*cmpfn)())); extern void jr_Heapify PROTO((jr_AList *heap, jr_int (*cmpfn)())); extern void jr_HeapPercolateDown PROTO((jr_AList *heap, jr_int node, jr_int (*cmpfn)())); extern void jr_HeapPercolateUp PROTO((jr_AList *heap, jr_int node, jr_int (*cmpfn)())); #define jr_HeapSize(heap) jr_AListSize(heap) #define jr_HeapElementSize(heap) jr_AListElementSize(heap) #define jr_HeapIsEmpty(heap) jr_AListIsEmpty(heap) #define jr_HeapIsEmpty(heap) jr_AListIsEmpty(heap) #define jr_HeapLastLeafIndex(heap) (jr_HeapSize(heap)-1) #define jr_HeapLastNodeIndex(heap) jr_HeapParentIndex(heap, jr_HeapLastLeafIndex(heap)) #define jr_HeapIsNodeIndex(heap, node) ((node) <= jr_HeapLastNodeIndex(heap)) #define jr_HeapIsRootIndex(heap, node) ((node) == 0) /* * changed below 1/19/94 to take dummy heap pointer for * added consistency. May break code using these macors * directly, however I hope they are only referenced in * the macros below. I already changed the references * in heap.c and heaptest.c */ #define jr_HeapRightChildIndex(heap, parent) (((parent) << 1) + 1) #define jr_HeapLeftChildIndex(heap, parent) (((parent) << 1) + 2) #define jr_HeapParentIndex(heap, child) (((child)-1) >> 1) #define jr_HeapElementPtr(heap, node) jr_AListElementPtr(heap, node) #define jr_HeapRightChildPtr(heap, p) jr_HeapElementPtr(heap, jr_HeapRightChildIndex(heap, p)) #define jr_HeapLeftChildPtr(heap, p) jr_HeapElementPtr(heap, jr_HeapLeftChildIndex(heap, p)) #define jr_HeapParentPtr(heap, child) jr_HeapElementPtr(heap, jr_HeapParentIndex(heap, child)) #define jr_HeapHasRightChildIndex(heap, parent) \ (jr_HeapRightChildIndex(heap, parent) < jr_HeapSize(heap)) #define jr_HeapHasLeftChildIndex(heap, parent) \ (jr_HeapLeftChildIndex(heap, parent) < jr_HeapSize(heap)) #define jr_HeapLastLeafPtr(heap) jr_HeapElementPtr(heap, jr_HeapLastLeafIndex(heap)) #endif
frankjas/libjr
include/jr/attribut.h
#ifndef __jr_attribute_h___ #define __jr_attribute_h___ #include "ezport.h" #include "jr/htable.h" #include "jr/dlist.h" typedef struct { jr_HTable string_table[1] ; jr_HTable attribute_table[1] ; jr_int next_list_id; } jr_AttributeManagerType ; typedef struct { jr_AttributeManagerType * manager ; jr_DList list_of_pairs[1] ; jr_int list_id; } jr_AttributeList ; typedef struct { char * name_string ; char * value_string ; jr_int list_id; } jr_AttributeType ; extern jr_AttributeManagerType *jr_AttributeManagerCreate PROTO((void)) ; extern void jr_AttributeManagerInit PROTO(( jr_AttributeManagerType * attribute_manager )) ; extern void jr_AttributeManagerDestroy PROTO(( jr_AttributeManagerType * attribute_manager )) ; extern void jr_AttributeManagerUndo PROTO(( jr_AttributeManagerType * attribute_manager )) ; extern const char * jr_AttributeManagerAddString PROTO(( jr_AttributeManagerType * attribute_manager, const char * string_arg, unsigned jr_int mask_arg )) ; extern void jr_AttributeManagerDeleteString PROTO(( jr_AttributeManagerType * attribute_manager, const char * string_arg )) ; #define jr_AttributeManagerAddNameString(mngr, string) \ jr_AttributeManagerAddString (mngr, string, jr_ATTRIBUTE_NAME) #define jr_AttributeManagerAddValueString(mngr, string) \ jr_AttributeManagerAddString (mngr, string, jr_ATTRIBUTE_VALUE) #define jr_AttributeManagerDeleteNameString(mngr, string) \ jr_AttributeManagerDeleteString (mngr, string) #define jr_AttributeManagerDeleteValueString(mngr, string) \ jr_AttributeManagerDeleteString (mngr, string) /******** Attribute List ********/ extern jr_AttributeList * jr_AttributeListCreate PROTO(( jr_AttributeManagerType * attribute_manager )) ; extern void jr_AttributeListInit PROTO(( jr_AttributeList * attribute_list, jr_AttributeManagerType * attribute_manager )) ; extern void jr_AttributeListDestroy PROTO(( jr_AttributeList * attribute_list )) ; extern void jr_AttributeListUndo PROTO(( jr_AttributeList * attribute_list )) ; extern void jr_AttributeListAddAttribute PROTO(( jr_AttributeList * list, const char * name_string, const char * value_string )) ; const char * jr_AttributeListGetValue PROTO (( jr_AttributeList * list, const char * name_string )); extern void jr_AttributeListDeleteAttribute PROTO (( jr_AttributeList * attribute_list, const char * name_string )); extern void jr_AttributeListEmpty PROTO (( jr_AttributeList * attribute_list )); #define jr_AttributeListForEachAttributePtr(attribute_list, attribute) \ jr_DListForEachElementPtr(attribute_list->list_of_pairs, attribute) #define jr_ATTRIBUTE_NAME 0x00000010 #define jr_ATTRIBUTE_VALUE 0x00000020 #define jr_AttributeNameString(attr) \ ((attr)->name_string) #define jr_AttributeValueString(attr) \ ((attr)->value_string) #endif
frankjas/libjr
libjr/misc/next2pow.c
#include "ezport.h" unsigned jr_int jr_next2power (number) unsigned jr_int number; { unsigned jr_int two_to_n = 1; for (; two_to_n < number; two_to_n <<= 1); return (two_to_n); } jr_int jr_is2power (number) unsigned jr_int number; { unsigned jr_int two_to_n = 1; for (; two_to_n < number; two_to_n <<= 1); if (two_to_n == number) return (1); else return (0); } unsigned jr_int jr_get2power (power) jr_int power; { unsigned jr_int two_to_n; jr_int i; two_to_n = 1; for (i=0; i < power; i++) { two_to_n <<= 1; } return (two_to_n); } unsigned jr_int jr_log_of_2_power (number) jr_int number; { jr_int log_value; log_value = 0; for (; number > 1; number >>= 1) { log_value ++; } return log_value; }
frankjas/libjr
libjr/string/skip.c
<filename>libjr/string/skip.c #include "ezport.h" #include <stdio.h> #include <ctype.h> #include "jr/string.h" char *jr_FirstNonWhiteSpacePtr(s) const char *s ; { while ((*s) && (isspace(*s))) s++ ; return((char*) s) ; } jr_int jr_FirstNonWhiteSpaceIndex(s) const char *s ; { jr_int n ; if (! *s) return(-1) ; for (n=0;*s;n++,s++) { if (! isspace(*s)) return(n) ; } return(n) ; } char * jr_FirstWhiteSpacePtr(s) const char *s ; { for(;*s;s++) { if (isspace(*s)) return((char *)s) ; } return(0) ; } jr_int jr_FirstWhiteSpaceIndex(s) const char *s ; { jr_int n ; for(n=0;*s;n++,s++) { if (isspace(*s)) return(n) ; } return(-1) ; } char *jr_NextNonWhiteSpacePtr (const char *s) { char * next_ptr; /* ** 1/24/07: Skip over non-white space followed by white-space */ next_ptr = jr_FirstWhiteSpacePtr (s); if (next_ptr) { next_ptr = jr_FirstNonWhiteSpacePtr (next_ptr); } return next_ptr; }
frankjas/libjr
libjr/syscalls/async_io.c
<filename>libjr/syscalls/async_io.c #include "async_io.h" static jr_HTable HandlerTable[1]; static jr_int InitializedTable = 0; struct sigaction OldAction[1]; jr_int jr_AddAsyncIOHandler (fd, fp, handler_fn, handler_param, is_for_reading, error_buf) jr_int fd; FILE * fp; void (*handler_fn) (); void * handler_param; jr_int is_for_reading; char * error_buf; { jr_AsyncInfoStruct tmp_handler_info[1]; jr_AsyncInfoStruct * handler_info; struct sigaction new_action[1]; sigset_t new_mask; sigset_t old_mask; jr_int sig_num; # ifdef has_streams_async_io sig_num = SIGPOLL; # else sig_num = SIGIO; # endif sigemptyset (&new_mask); sigaddset (&new_mask, sig_num); sigprocmask (SIG_BLOCK, &new_mask, &old_mask); { if (!InitializedTable) { InitializedTable = 1; jr_HTableInit ( HandlerTable, sizeof (jr_AsyncInfoStruct), jr_AsyncInfoHash, jr_AsyncInfoCmp ); new_action->sa_handler = jr_AsyncIOHandler; sigemptyset (&new_action->sa_mask); new_action->sa_flags = SA_RESTART; sigaction (sig_num, new_action, OldAction); } jr_AsyncInfoInit (tmp_handler_info, fd, fp, handler_fn, handler_param, is_for_reading); handler_info = jr_HTableFindElementPtr (HandlerTable, tmp_handler_info); if (handler_info) { jr_esprintf (error_buf, "file descriptor %d already has handler", fd); jr_AsyncInfoUndo (tmp_handler_info); sigprocmask (SIG_SETMASK, &old_mask, 0); return -1; } jr_HTableSetNewElement (HandlerTable, tmp_handler_info); } sigprocmask (SIG_SETMASK, &old_mask, 0); return 0; } void jr_RemoveAsyncIOHandler (fd, is_for_reading) jr_int fd; jr_int is_for_reading; { jr_AsyncInfoStruct tmp_handler_info[1]; jr_AsyncInfoStruct * handler_info; sigset_t new_mask; sigset_t old_mask; jr_int sig_num; if (!InitializedTable) { return; } # ifdef has_streams_async_io sig_num = SIGPOLL; # else sig_num = SIGIO; # endif sigemptyset (&new_mask); sigaddset (&new_mask, sig_num); sigprocmask (SIG_BLOCK, &new_mask, &old_mask); { jr_AsyncInfoInit (tmp_handler_info, fd, 0, 0, 0, is_for_reading); handler_info = jr_HTableDeleteElement (HandlerTable, tmp_handler_info); jr_AsyncInfoUndo (tmp_handler_info); if (handler_info) { jr_AsyncInfoUndo (handler_info); } if (jr_HTableSize (HandlerTable) == 0) { sigaction (sig_num, OldAction, 0); jr_HTableUndo (HandlerTable); InitializedTable = 0; } } sigprocmask (SIG_SETMASK, &old_mask, 0); } void jr_AsyncIOHandler (sig_number) jr_int sig_number; { jr_AsyncInfoStruct * handler_info; fd_set read_fds; fd_set write_fds; fd_set exception_fds; struct timeval timeout; int n_ready; jr_int max_fd = -1; if (!InitializedTable) { return; } FD_ZERO (&read_fds); FD_ZERO (&write_fds); /* or pass a 0 to select */ FD_ZERO (&exception_fds); /* or pass a 0 to select */ jr_HTableForEachElementPtr (HandlerTable, handler_info) { if (handler_info->is_for_reading) { FD_SET (handler_info->fd, &read_fds); if (handler_info->fd > max_fd) { max_fd = handler_info->fd; } } else { FD_SET (handler_info->fd, &write_fds); if (handler_info->fd > max_fd) { max_fd = handler_info->fd; } } } timeout.tv_sec = 0; timeout.tv_usec = 0; while (1) { /* infinite loop to restart if interrupted */ n_ready = select ( max_fd + 1, &read_fds, &write_fds, &exception_fds, &timeout ); if (n_ready < 0) { if (errno == EINTR) { /* * select is interrupted by signals * and not restarted even under BSD */ continue; } return; } if (n_ready == 0) { return; } if (n_ready > 0) { break; } } if (n_ready == 0) { return; } jr_HTableForEachElementPtr (HandlerTable, handler_info) { if ( FD_ISSET (handler_info->fd, &read_fds) && handler_info->is_for_reading) { if (handler_info->fp) { (*handler_info->handler_fn) (handler_info->fp, handler_info->handler_param); } else { (*handler_info->handler_fn) (handler_info->fd, handler_info->handler_param); } } if ( FD_ISSET (handler_info->fd, &write_fds) && !handler_info->is_for_reading) { if (handler_info->fp) { (*handler_info->handler_fn) (handler_info->fp, handler_info->handler_param); } else { (*handler_info->handler_fn) (handler_info->fd, handler_info->handler_param); } } } if ( OldAction->sa_handler != SIG_DFL && OldAction->sa_handler != SIG_IGN) { (*OldAction->sa_handler) (sig_number); } } void jr_AsyncInfoInit (handler_info, fd, fp, handler_fn, handler_param, is_for_reading) jr_AsyncInfoStruct * handler_info; jr_int fd; FILE * fp; void (*handler_fn) (); void * handler_param; jr_int is_for_reading; { handler_info->fd = fd; handler_info->fp = fp; handler_info->handler_fn = handler_fn; handler_info->handler_param = handler_param; handler_info->is_for_reading = is_for_reading; } void jr_AsyncInfoUndo (handler_info) jr_AsyncInfoStruct * handler_info; { } jr_int jr_AsyncInfoHash (void_arg_1) const void * void_arg_1; { const jr_AsyncInfoStruct * handler_info = void_arg_1; jr_int hash_value = 0; hash_value += handler_info->fd; hash_value += handler_info->is_for_reading; return hash_value; } jr_int jr_AsyncInfoCmp (void_arg_1, void_arg_2) const void * void_arg_1; const void * void_arg_2; { const jr_AsyncInfoStruct * handler_info_1 = void_arg_1; const jr_AsyncInfoStruct * handler_info_2 = void_arg_2; jr_int diff; diff = handler_info_1->fd - handler_info_2->fd; if (diff != 0) { return diff; } diff = handler_info_1->is_for_reading - handler_info_2->is_for_reading; if (diff != 0) { return diff; } return 0; } void jr_BlockAsyncIO (old_mask_ptr) void * old_mask_ptr; { sigset_t new_mask; jr_int sig_num; # ifdef has_streams_async_io sig_num = SIGPOLL; # else sig_num = SIGIO; # endif sigemptyset (&new_mask); sigaddset (&new_mask, sig_num); sigprocmask (SIG_BLOCK, &new_mask, old_mask_ptr); } void jr_UnBlockAsyncIO (old_mask_ptr) void * old_mask_ptr; { sigprocmask (SIG_SETMASK, old_mask_ptr, 0); } # ifdef has_streams_async_io #include <sys/types.h> #include <stropts.h> #include <sys/conf.h> jr_int jr_InitAsyncIO (fd, fp, handler_fn, handler_param, is_for_reading, error_buf) jr_int fd; FILE * fp; void (*handler_fn) (); void * handler_param; jr_int is_for_reading; char * error_buf; { jr_int status; jr_int ioctl_args = 0; status = jr_AddAsyncIOHandler (fd, fp, handler_fn, handler_param, is_for_reading, error_buf); if (status != 0) { return -1; } /* * Set the handler before setting the enabling * the generation of SIGPOLL. */ if (is_for_reading) { ioctl_arg |= S_RDNORM; } else { ioctl_arg |= S_WRNORM; } status = ioctl (fd, I_SETSIG, ioctl_args); if (status != 0) { jr_esprintf (error_buf, "couldn't ioctl (%d, I_SETSIG): %s", fd, strerror (errno) ); jr_FileDescUnSetAsyncHandler (fd); return -1; } return 0; } jr_int jr_UndoAsyncIO (fd, is_for_reading, error_buf) jr_int fd; jr_int is_for_reading; char * error_buf; { jr_RemoteAsyncHandler (fd, is_for_reading); status = ioctl (fd, I_SETSIG, 0); if (status != 0) { jr_esprintf (error_buf, "couldn't ioctl (%d, I_SETSIG): %s", fd, strerror (errno) ); return -1; } return 0; } #else jr_int jr_InitAsyncIO (fd, fp, handler_fn, handler_param, is_for_reading, error_buf) jr_int fd; FILE * fp; void (*handler_fn) (); void * handler_param; jr_int is_for_reading; char * error_buf; { jr_int open_flags; jr_int status; open_flags = fcntl (fd, F_GETFL, 0); if (open_flags == -1) { jr_esprintf (error_buf, "couldn't fcntl (%d, F_GETFL): %s", fd, strerror (errno) ); return -1; } open_flags |= FASYNC; status = fcntl (fd, F_SETFL, open_flags); if (status == -1) { jr_esprintf (error_buf, "couldn't fcntl (%d, F_SETFL): %s", fd, strerror (errno) ); return -1; } status = jr_AddAsyncIOHandler (fd, fp, handler_fn, handler_param, is_for_reading, error_buf); if (status != 0) { return -1; } /* * Set the handler before setting the enabling * the generation of SIGIO. */ status = fcntl (fd, F_SETOWN, getpid ()); /* * tell device driver which process should receive SIGIO */ if (status == -1) { jr_esprintf (error_buf, "couldn't fcntl (%d, F_SETOWN): %s", fd, strerror (errno) ); jr_RemoveAsyncIOHandler (fd, is_for_reading); return -1; } return 0; } jr_int jr_UndoAsyncIO (fd, is_for_reading, error_buf) jr_int fd; jr_int is_for_reading; char * error_buf; { jr_int open_flags; jr_int status; jr_RemoveAsyncIOHandler (fd, is_for_reading); open_flags = fcntl (fd, F_GETFL, 0); if (open_flags == -1) { jr_esprintf (error_buf, "couldn't fcntl (%d, F_GETFL): %s", fd, strerror (errno) ); return -1; } open_flags |= FASYNC; status = fcntl (fd, F_SETFL, open_flags); if (status == -1) { jr_esprintf (error_buf, "couldn't fcntl (%d, F_SETFL): %s", fd, strerror (errno) ); return -1; } return 0; } # endif
frankjas/libjr
libjr/replace/getpgrp.c
<gh_stars>0 #define _POSIX_SOURCE 1 #include "ezport.h" #ifdef replace_bsd_getpgrp #include <sys/types.h> pid_t jr_getpgrp() { return jr_bsd_getpgrp(0) ; } #undef getpgrp int jr_bsd_getpgrp () { /* * bsd's version takes a process id * 0 means current process */ extern int getpgrp (); return getpgrp (0); } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/struct/att_mngr.c
<reponame>frankjas/libjr #include "att_mngr.h" jr_AttributeManagerType * jr_AttributeManagerCreate() { jr_AttributeManagerType * new_manager ; new_manager = (jr_AttributeManagerType *) jr_malloc(sizeof(jr_AttributeManagerType)) ; jr_AttributeManagerInit(new_manager) ; return(new_manager) ; } void jr_AttributeManagerInit(manager) jr_AttributeManagerType * manager ; { memset (manager, 0, sizeof (*manager)); jr_HTableInit ( manager->string_table, sizeof (jr_StringRefsStruct), jr_StringRefsHash, jr_StringRefsCmp ) ; jr_HTableInitForPtrValues (manager->attribute_table, jr_AttributeHash, jr_AttributeCmp) ; manager->next_list_id = 1; } void jr_AttributeManagerUndo(manager) jr_AttributeManagerType * manager ; { jr_StringRefsStruct * string_info; jr_HTableForEachElementPtr(manager->string_table, string_info) { jr_StringRefsUndo (string_info); } jr_HTableUndo(manager->string_table) ; jr_HTableUndo(manager->attribute_table) ; } void jr_AttributeManagerDestroy(manager) jr_AttributeManagerType * manager ; { jr_AttributeManagerUndo(manager) ; jr_free(manager) ; } const char * jr_AttributeManagerAddString(manager, string_arg, mask_arg) jr_AttributeManagerType * manager ; const char * string_arg ; unsigned jr_int mask_arg ; { jr_StringRefsStruct tmp_string_info[1]; jr_StringRefsStruct * string_info; jr_StringRefsInit (tmp_string_info, string_arg); string_info = jr_HTableFindElementPtr (manager->string_table, tmp_string_info); if (string_info == 0) { string_info = jr_HTableSetNewElement (manager->string_table, tmp_string_info); } else { jr_StringRefsUndo (tmp_string_info); } string_info->num_references++; string_info->mask_value |= mask_arg; return string_info->string; } void jr_AttributeManagerDeleteString(manager, string_arg) jr_AttributeManagerType * manager ; const char * string_arg ; { jr_StringRefsStruct tmp_string_info[1]; jr_StringRefsStruct * string_info; jr_int index; jr_StringRefsInit (tmp_string_info, string_arg); index = jr_HTableFindElementIndex (manager->string_table, tmp_string_info); if (index >= 0) { string_info = jr_HTableElementPtr (manager->string_table, index); string_info->num_references--; if (string_info->num_references <= 0) { jr_StringRefsUndo (string_info); jr_HTableDeleteIndex (manager->string_table, index); } } jr_StringRefsUndo (tmp_string_info); } jr_int jr_AttributeManagerGetListId (manager) jr_AttributeManagerType * manager ; { jr_int next_list_id; next_list_id = manager->next_list_id; manager->next_list_id ++; return next_list_id; } void jr_AttributeManagerAddAttribute (manager, attribute_ptr) jr_AttributeManagerType * manager ; jr_AttributeType * attribute_ptr; { jr_HTableNewPtrValueIndex (manager->attribute_table, attribute_ptr); } jr_AttributeType *jr_AttributeManagerFindAttribute (manager, list_id, name_string) jr_AttributeManagerType * manager ; jr_int list_id; const char * name_string; { jr_AttributeType tmp_attribute[1]; jr_AttributeType * attribute_ptr; jr_int table_index; tmp_attribute->list_id = list_id; tmp_attribute->name_string = (char *) name_string; table_index = jr_HTableFindPtrValueIndex ( manager->attribute_table, tmp_attribute ); if (table_index < 0) { return 0; } attribute_ptr = jr_HTableKeyPtrValue (manager->attribute_table, table_index); return attribute_ptr; } void jr_AttributeManagerDeleteAttribute (manager, attribute_ptr) jr_AttributeManagerType * manager ; jr_AttributeType * attribute_ptr; { jr_HTableDeletePtrValue (manager->attribute_table, attribute_ptr); } void jr_StringRefsInit (string_info, string) jr_StringRefsStruct * string_info; const char * string; { string_info->string = jr_strdup (string); string_info->mask_value = 0; string_info->num_references = 0; } void jr_StringRefsUndo (string_info) jr_StringRefsStruct * string_info; { jr_free (string_info->string); } jr_int jr_StringRefsHash (void_arg_1) const void * void_arg_1; { const jr_StringRefsStruct * string_info = void_arg_1; return jr_strhash_pjw (string_info->string); } jr_int jr_StringRefsCmp (void_arg_1, void_arg_2) const void * void_arg_1; const void * void_arg_2; { const jr_StringRefsStruct * string_info_1 = void_arg_1; const jr_StringRefsStruct * string_info_2 = void_arg_2; return strcmp (string_info_1->string, string_info_2->string); } jr_int jr_AttributeHash (void_arg_1) const void * void_arg_1; { const jr_AttributeType * attribute_ptr = void_arg_1; jr_int hash_value = 0; hash_value += attribute_ptr->list_id; hash_value += jr_strhash_pjw (attribute_ptr->name_string); return hash_value; } jr_int jr_AttributeCmp (void_arg_1, void_arg_2) const void * void_arg_1; const void * void_arg_2; { const jr_AttributeType * attribute_ptr_1 = void_arg_1; const jr_AttributeType * attribute_ptr_2 = void_arg_2; jr_int diff; diff = attribute_ptr_1->list_id - attribute_ptr_2->list_id; if (diff != 0) { return diff; } diff = strcmp (attribute_ptr_1->name_string, attribute_ptr_2->name_string); if (diff != 0) { return diff; } return 0; }
frankjas/libjr
libjr/io/mailhost.c
<gh_stars>0 #define _POSIX_SOURCE 1 #include "ezport.h" #include <errno.h> #include <sys/types.h> #include <string.h> #include <stdlib.h> #include <netinet/in.h> #include <arpa/nameser.h> #include <resolv.h> #include "jr/io.h" #include "jr/alist.h" #include "jr/string.h" #include "jr/malloc.h" #include "jr/inetlib.h" #include "jr/mail.h" #include "jr/misc.h" #include "jr/nettype.h" #include "mailproj.h" #define MAX_RESPONSE_SIZE 8192 #ifndef HFIXEDSZ # define HFIXEDSZ 12 /* sizeof (HEADER) */ #endif #ifndef INT16SZ # define INT16SZ 2 /* from sendmail code */ #endif #ifndef INT32SZ # define INT32SZ 4 /* from sendmail code */ #endif jr_int jr_MailGetMailExchanger (host_name, smtp_server_name, smtp_server_name_length, error_buf) const char * host_name; char * smtp_server_name; jr_int smtp_server_name_length; char * error_buf; { jr_MX_EntryListType mx_entry_list[1]; jr_MX_EntryType * mx_entry_ptr; jr_int status; jr_MX_EntryListInit (mx_entry_list); status = jr_MX_EntryListLoadHostNameInfo (mx_entry_list, host_name, error_buf); if (status != 0) { goto return_status; } jr_MX_EntryListSortByPreference (mx_entry_list); mx_entry_ptr = jr_MX_EntryListFirstEntryPtr (mx_entry_list); strncpy (smtp_server_name, jr_MX_EntryName (mx_entry_ptr), smtp_server_name_length); smtp_server_name [smtp_server_name_length - 1] = 0; status = 0; return_status : { jr_MX_EntryListUndo (mx_entry_list); } return status; } void jr_MX_EntryListInit (mx_entry_list) jr_MX_EntryListType * mx_entry_list; { jr_AListInit (mx_entry_list->list_field, sizeof (jr_MX_EntryType)); } void jr_MX_EntryListUndo (mx_entry_list) jr_MX_EntryListType * mx_entry_list; { jr_MX_EntryType * mx_entry_ptr; jr_AListForEachElementPtr (mx_entry_list->list_field, mx_entry_ptr) { jr_MX_EntryUndo (mx_entry_ptr); } jr_AListUndo (mx_entry_list->list_field); } void jr_MX_EntryListAddEntry (mx_entry_list, mx_name, mx_preference) jr_MX_EntryListType * mx_entry_list; const char * mx_name; jr_int mx_preference; { jr_MX_EntryType * mx_entry_ptr; mx_entry_ptr = jr_AListNewTailPtr (mx_entry_list->list_field); jr_MX_EntryInit (mx_entry_ptr, mx_name, mx_preference); } void jr_MX_EntryListSetInetAddress (mx_entry_list, mx_name, inet_addr_number) jr_MX_EntryListType * mx_entry_list; const char * mx_name; jr_int inet_addr_number; { jr_MX_EntryType * mx_entry_ptr; jr_MX_EntryListForEachEntryPtr (mx_entry_list, mx_entry_ptr) { if (strcasecmp (mx_name, jr_MX_EntryName (mx_entry_ptr)) == 0) { jr_MX_EntrySetInetAddrNumber (mx_entry_ptr, inet_addr_number); } } } jr_int jr_MX_EntryListLoadHostNameInfo (mx_entry_list, host_name, error_buf) jr_MX_EntryListType * mx_entry_list; const char * host_name; char * error_buf; { unsigned char * response_buffer = 0; unsigned jr_int max_response_length = MAX_RESPONSE_SIZE; unsigned jr_int response_length; char * tmp_name_ptr = 0; HEADER * header_ptr; unsigned char * curr_ptr; unsigned char * end_ptr; jr_int answer_type; jr_int answer_length; jr_int num_question_entries; jr_int num_answer_entries; jr_int mx_preference; jr_int j; jr_int status; if (max_response_length < sizeof (HEADER)) { max_response_length = sizeof (HEADER); } response_buffer = jr_malloc (max_response_length); tmp_name_ptr = jr_malloc (max_response_length); status = res_query (host_name, C_IN, T_MX, response_buffer, max_response_length); if (status < 0) { jr_esprintf (error_buf, "couldn't get MX info for '%.32s", host_name); goto return_status; } response_length = status; if (response_length > max_response_length) { jr_esprintf (error_buf, "res_query() response length %d > max. of %d passed in!", response_length, max_response_length ); status = jr_INET_SYSTEM_ERROR; goto return_status; } header_ptr = (void *) response_buffer; num_question_entries = jr_ntohs (header_ptr->qdcount); num_answer_entries = jr_ntohs (header_ptr->ancount); curr_ptr = response_buffer + HFIXEDSZ; end_ptr = response_buffer + response_length; for (j=0; j < num_question_entries; j++) { status = dn_skipname(curr_ptr, end_ptr); if (status < 0) { status = jr_INET_HOST_NOT_FOUND; jr_esprintf (error_buf, "no MX entries found"); goto return_status; } curr_ptr += status + QFIXEDSZ; } for (j=0; j < num_answer_entries; j++) { if (curr_ptr >= end_ptr) { break; } status = dn_expand (response_buffer, end_ptr, curr_ptr, tmp_name_ptr, max_response_length); if (status < 0) { break; } curr_ptr += status; GETSHORT (answer_type, curr_ptr); curr_ptr += INT16SZ + INT32SZ; /* * Skip over the 'class' value and the 'ttl' value * Class is: C_IN, C_CHAOS, C_HS, C_HESIOD, C_ANY, C_NONE. * (from 'bind' source, lib/resolv/res_debug.c, * def. for 'struct res_sym __p_class_syms[]' array. */ GETSHORT (answer_length, curr_ptr); switch (answer_type) { /* * Look in source for 'bind', function Print_rr() in bin/nslookup/debug.c * for code to interpret each type of nameserver record. */ case T_A : { jr_int inet_addr_number; GETLONG (inet_addr_number, curr_ptr); jr_MX_EntryListSetInetAddress (mx_entry_list, tmp_name_ptr, inet_addr_number); /* * tmp_name_ptr contains the name of the mx entry with this address */ curr_ptr += answer_length; break; } case T_MX : { GETSHORT (mx_preference, curr_ptr); status = dn_expand ( response_buffer, end_ptr, curr_ptr, tmp_name_ptr, max_response_length ); if (status < 0) { goto return_list; } curr_ptr += status; jr_MX_EntryListAddEntry (mx_entry_list, tmp_name_ptr, mx_preference); break; } default : { curr_ptr += answer_length; break; } } } return_list : if (jr_MX_EntryListIsEmpty (mx_entry_list)) { status = jr_INET_HOST_NOT_FOUND; jr_esprintf (error_buf, "no MX entries found"); goto return_status; } status = 0; return_status : { if (response_buffer) { jr_free (response_buffer); } if (tmp_name_ptr) { jr_free (tmp_name_ptr); } } return status; } jr_int jr_MX_EntryListSetInetAddrNumbers (mx_entry_list, error_buf) jr_MX_EntryListType * mx_entry_list; char * error_buf; { jr_MX_EntryType * mx_entry_ptr; struct sockaddr_in sockaddr_info[1] ; jr_int status ; jr_MX_EntryListForEachEntryPtr (mx_entry_list, mx_entry_ptr) { if (jr_MX_EntryInetAddrNumber (mx_entry_ptr) == 0) { status = jr_InetAddressInit ( sockaddr_info, jr_MX_EntryName (mx_entry_ptr), SMTP_PORT, error_buf ); if (status != 0) { jr_esprintf (error_buf, "couldn't get inet address for '%.32s': %s", jr_MX_EntryName (mx_entry_ptr), error_buf ); return status; } jr_MX_EntrySetInetAddrNumber ( mx_entry_ptr, sockaddr_info->sin_addr.s_addr ); } } return 0; } void jr_MX_EntryInit (mx_entry_ptr, mx_name, mx_preference) jr_MX_EntryType * mx_entry_ptr; const char * mx_name; jr_int mx_preference; { memset (mx_entry_ptr, 0, sizeof (*mx_entry_ptr)); mx_entry_ptr->mx_name = jr_strdup (mx_name); mx_entry_ptr->mx_preference = mx_preference; } void jr_MX_EntryUndo (mx_entry_ptr) jr_MX_EntryType * mx_entry_ptr; { jr_free (mx_entry_ptr->mx_name); } jr_int jr_MX_EntryPreferenceCmp (void_ptr_1, void_ptr_2) const void * void_ptr_1; const void * void_ptr_2; { const jr_MX_EntryType * mx_entry_ptr_1 = void_ptr_1; const jr_MX_EntryType * mx_entry_ptr_2 = void_ptr_2; if (mx_entry_ptr_1->mx_preference < mx_entry_ptr_2->mx_preference) { return -1; } if (mx_entry_ptr_1->mx_preference > mx_entry_ptr_2->mx_preference) { return 1; } return 0; } #ifdef __sendmail_original_code /* * This is what the above mail exchanger code was based on. * Stolen from sendmail's getmxrr() */ #include <sysexits.h> #include <netinet/in.h> /* * for EX_OK, etc. constants */ #include <netdb.h> #define RES_UNC_T char * #define SIZE_T size_t #define FALSE 0 #define TRUE (! FALSE) #define MAXPACKET 8192 /* max packet size used internally by BIND */ #define MAXMXHOSTS 100 #define MXHOSTBUFSIZE (128 * MAXMXHOSTS) #define MAXSHORTSTR 203 #define tTd(flag, level) 0 /* JR - for diagnostic levels */ #define sm_gethostbyname(n) gethostbyname (n) #define UseNameServer 1 #define HasWildcardMX 0 /* don't use MX records when canonifying */ #define ConfigLevel 8 /* JR - the config file level, refers to sendmail version? */ static char * FallBackMX; static char * MyHostName; static jr_int TryNullMXList = 0; static char MXHostBuf[MXHOSTBUFSIZE]; #define syserr printf typedef union { HEADER qb1; /* JR - declared in arpa/nameser.h */ u_char qb2[MAXPACKET]; } querybuf; typedef jr_int bool; extern int h_errno; extern int res_query(), res_search(); extern int mxrand __P((char *)); jr_int getmxrr(host, mxhosts, droplocalhost, rcode) char * host; char ** mxhosts; jr_int droplocalhost; jr_int * rcode; { unsigned char * eom; unsigned char * cp; jr_int i; jr_int j; jr_int n; jr_int nmx = 0; char * bp; HEADER * hp; querybuf answer; jr_int ancount; jr_int qdcount; jr_int buflen; jr_int seenlocal = FALSE; unsigned jr_short pref; unsigned jr_short type; unsigned jr_short localpref = 256; char * fallbackMX = FallBackMX; jr_int trycanon = FALSE; jr_int (*resfunc)(); unsigned jr_short prefer[MAXMXHOSTS]; jr_int weight[MAXMXHOSTS]; if (tTd(8, 2)) { printf("getmxrr(%s, droplocalhost=%d)\n", host, droplocalhost); } if ( fallbackMX != NULL && droplocalhost && wordinclass(fallbackMX, 'w')) { /* don't use fallback for this pass */ fallbackMX = NULL; } *rcode = EX_OK; /* efficiency hack -- numeric or non-MX lookups */ if (host[0] == '[') { goto punt; } /* ** If we don't have MX records in our host switch, don't ** try for MX records. Note that this really isn't "right", ** since we might be set up to try NIS first and then DNS; ** if the host is found in NIS we really shouldn't be doing ** MX lookups. However, that should be a degenerate case. */ if (!UseNameServer) { goto punt; } if (HasWildcardMX && ConfigLevel >= 6) { resfunc = res_query; } else { resfunc = res_search; } errno = 0; n = (*resfunc)(host, C_IN, T_MX, (u_char *) &answer, sizeof(answer)); if (n < 0) { if (tTd(8, 1)) { printf("getmxrr: res_search(%s) failed (errno=%d, h_errno=%d)\n", (host == NULL) ? "<NULL>" : host, errno, h_errno ); } switch (h_errno) { case NO_DATA: trycanon = TRUE; /* fall through */ case NO_RECOVERY: /* no MX data on this host */ goto punt; case HOST_NOT_FOUND: # if BROKEN_RES_SEARCH case 0: /* Ultrix resolver retns failure w/ h_errno=0 */ # endif /* host doesn't exist in DNS; might be in /etc/hosts */ trycanon = TRUE; *rcode = EX_NOHOST; goto punt; case TRY_AGAIN: case -1: /* couldn't connect to the name server */ if (fallbackMX != NULL) { /* name server is hosed -- push to fallback */ mxhosts[nmx++] = fallbackMX; return nmx; } /* it might come up later; better queue it up */ *rcode = EX_TEMPFAIL; break; default: syserr("getmxrr: res_search (%s) failed with impossible h_errno (%d)\n", host, h_errno ); *rcode = EX_OSERR; break; } /* irreconcilable differences */ return (-1); } /* avoid problems after truncation in tcp packets */ if (n > sizeof(answer)) { n = sizeof(answer); } # ifdef _garbage__ unsigned qdcount :16; /* number of question entries */ unsigned ancount :16; /* number of answer entries */ unsigned nscount :16; /* number of authority entries */ unsigned arcount :16; /* number of resource entries */ # endif /* find first satisfactory answer */ hp = (HEADER *)&answer; cp = (u_char *)&answer + HFIXEDSZ; eom = (u_char *)&answer + n; qdcount = jr_ntohs(hp->qdcount); ancount = jr_ntohs(hp->ancount); for (j=0; j < qdcount; j++; cp += n + QFIXEDSZ) { if ((n = dn_skipname(cp, eom)) < 0) { goto punt; } } buflen = sizeof(MXHostBuf) - 1; bp = MXHostBuf; for (j=0; j < ancount; j++) { if (cp >= eom || nmx >= MAXMXHOSTS - 1) { break; } if ((n = dn_expand((u_char *)&answer, eom, cp, (RES_UNC_T) bp, buflen)) < 0) { break; } cp += n; GETSHORT(type, cp); cp += INT16SZ + INT32SZ; GETSHORT(n, cp); if (type != T_MX) { if (tTd(8, 8) || _res.options & RES_DEBUG) { printf("unexpected answer type %d, size %d\n", type, n); } cp += n; continue; } GETSHORT(pref, cp); if ((n = dn_expand((u_char *)&answer, eom, cp, (RES_UNC_T) bp, buflen)) < 0) { break; } cp += n; if (wordinclass(bp, 'w')) { if (tTd(8, 3)) { printf("found localhost (%s) in MX list, pref=%d\n", bp, pref); } if (droplocalhost) { if (!seenlocal || pref < localpref) { localpref = pref; } seenlocal = TRUE; continue; } weight[nmx] = 0; } else { weight[nmx] = mxrand(bp); } prefer[nmx] = pref; mxhosts[nmx++] = bp; n = strlen(bp); bp += n; if (bp[-1] != '.') { *bp++ = '.'; n++; } *bp++ = '\0'; buflen -= n + 1; } /* sort the records */ for (i = 0; i < nmx; i++) { for (j = i + 1; j < nmx; j++) { if ( prefer[i] > prefer[j] || (prefer[i] == prefer[j] && weight[i] > weight[j])) { jr_int temp; char * temp1; temp = prefer[i]; prefer[i] = prefer[j]; prefer[j] = temp; temp1 = mxhosts[i]; mxhosts[i] = mxhosts[j]; mxhosts[j] = temp1; temp = weight[i]; weight[i] = weight[j]; weight[j] = temp; } } if (seenlocal && prefer[i] >= localpref) { /* truncate higher preference part of list */ nmx = i; } } /* delete duplicates from list (yes, some bozos have duplicates) */ for (i = 0; i < nmx - 1; ) { if (strcasecmp(mxhosts[i], mxhosts[i + 1]) != 0) { i++; } else { /* compress out duplicate */ for (j = i + 1; j < nmx; j++) { mxhosts[j] = mxhosts[j + 1]; } nmx--; } } if (nmx == 0) punt: { if ( seenlocal && (!TryNullMXList || sm_gethostbyname(host) == NULL)) { /* ** If we have deleted all MX entries, this is ** an error -- we should NEVER send to a host that ** has an MX, and this should have been caught ** earlier in the config file. ** ** Some sites prefer to go ahead and try the ** A record anyway; that case is handled by ** setting TryNullMXList. I believe this is a ** bad idea, but it's up to you.... */ *rcode = EX_CONFIG; syserr("MX list for %s points back to %s", host, MyHostName); return -1; } if (strlen(host) >= (SIZE_T) sizeof MXHostBuf) { *rcode = EX_CONFIG; syserr("Host name %s too long", shortenstring(host, MAXSHORTSTR)); return -1; } snprintf(MXHostBuf, sizeof MXHostBuf, "%s", host); mxhosts[0] = MXHostBuf; if (host[0] == '[') { register char *p; /* this may be an MX suppression-style address */ p = strchr(MXHostBuf, ']'); if (p != NULL) { *p = '\0'; if (inet_addr(&MXHostBuf[1]) != INADDR_NONE) { nmx++; *p = ']'; } else { trycanon = TRUE; mxhosts[0]++; } } } if (trycanon && getcanonname(mxhosts[0], sizeof MXHostBuf - 2, FALSE)) { bp = &MXHostBuf[strlen(MXHostBuf)]; if (bp[-1] != '.') { *bp++ = '.'; *bp = '\0'; } nmx = 1; } } /* if we have a default lowest preference, include that */ if (fallbackMX != NULL && !seenlocal) { mxhosts[nmx++] = fallbackMX; } return (nmx); } #endif
frankjas/libjr
libjr/dlist/dlistsrt.c
#include "project.h" void *jr_DListFindInsertPtr (list, obj, cmpfn) jr_DList * list; void * obj; jr_int (*cmpfn) (); { char * current; jr_DListForEachElementPtr (list, current) { if ((*cmpfn) (obj, current) <= 0) return (current); } return (current); } void *jr_DListNewElementPtrInOrderWithSizeAndUniqueFlag (list, obj, cmpfn, size, unique) jr_DList * list; void * obj; jr_int (*cmpfn) (); jr_int size; jr_int unique; { void * next; void * new; next = jr_DListFindInsertPtr (list, obj, cmpfn); if (next && unique) { if ((*cmpfn) (obj, next) == 0) return (next); /* next is the same as obj */ } new = (void *) jr_DListNewPrevElementPtrWithSize (list, next, size); return (new); }
frankjas/libjr
libjr/missing/putenv.c
<filename>libjr/missing/putenv.c #define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_putenv /* putenv should be declared extern in unistd.h */ #include <string.h> #include <unistd.h> int putenv(name_value_pair_str) char * name_value_pair_str; { jr_int name_length ; char * temp_char_ptr ; char ** new_environ_ptr ; extern char ** environ ; jr_int old_vector_length; jr_int new_vector_length ; jr_int i ; /* First see if there is an existing 'name=value' with the * same name as s. */ for (temp_char_ptr = name_value_pair_str; (*temp_char_ptr != '=') && (*temp_char_ptr != '\0'); temp_char_ptr++) { /* skip up to equals sign or null */ ; } if (*temp_char_ptr == '=') { name_length = (temp_char_ptr - name_value_pair_str) + 1; for (i = 0; environ[i] != 0; i++) { if (strncmp(environ[i], name_value_pair_str, name_length) == 0) { environ[i] = name_value_pair_str ; return(0) ; } } old_vector_length = i; } else { for (i = 0; environ[i] != 0; i++); old_vector_length = i; } new_environ_ptr = (char **) malloc((old_vector_length + 2) * sizeof(char *)); if (new_environ_ptr == NULL) { return(-1) ; } for (i = 0; i < old_vector_length; i++) { new_environ_ptr[i] = environ[i] ; } new_vector_length = old_vector_length + 1 ; new_environ_ptr[old_vector_length] = name_value_pair_str ; new_environ_ptr[new_vector_length] = 0 ; environ = new_environ_ptr ; return(0); } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/misc/hashint.c
#include "ezport.h" #include "jr/misc.h" /* Author: <NAME> Creation Date: March 1987 Modified: <NAME>, May 1989 */ jr_int jr_inthash (i) jr_int i; { if (i < 0) { i = -i ; i >>= 1 ; } return(i) ; } jr_int jr_intphash (void_arg_1) const void * void_arg_1; { const jr_int * i_ptr = void_arg_1; jr_int i = *i_ptr ; if (i < 0) { i = -i ; i >>= 1 ; } return(i) ; }
frankjas/libjr
libjr/string/vdeclare.c
<reponame>frankjas/libjr #include "ezport.h" #include <stdio.h> #include <string.h> #include <sys/types.h> #include "jr/vector.h" #include "jr/string.h" #include "jr/malloc.h" extern size_t strlen PROTO((const char *)) ; void jr_VectorPrintDeclaration(wfp, string_vector, variable_name) FILE * wfp ; const char ** string_vector ; const char * variable_name ; { char padding[128] ; char * escaped_version ; jr_int vector_length; jr_int max_length; jr_int current_length ; jr_int num_blanks ; char ** vp ; vector_length = jr_VectorLength(string_vector) ; max_length = jr_VectorFindMaximum(string_vector, vector_length, (jr_int (*) ()) strlen) ; /* build padding string */ { jr_int i ; for (i=0; i < (jr_int) (sizeof(padding)-1); i++) { padding[i] = ' ' ; } padding[i] = 0 ; } fprintf(wfp, "char * %s[] = {\n", variable_name) ; for (vp = (char **) string_vector ; *vp ; vp++) { current_length = (jr_int) strlen(*vp) ; escaped_version = (char *) jr_malloc(2 * current_length) ; strcpy(escaped_version, *vp) ; num_blanks = (max_length - current_length) ; if (num_blanks < 0) num_blanks = 0 ; /* change newlines and such into the backslash equivalents */ jr_ControlCharsToEscapedChars(escaped_version) ; fprintf(wfp,"\t\t\"%s\",\n", escaped_version) ; jr_free(escaped_version) ; } fprintf(wfp, "\t\t(char *) 0\n") ; fprintf(wfp, "} ;\n") ; }
frankjas/libjr
include/jr/trace.h
<filename>include/jr/trace.h #ifndef _jr_traceh #define _jr_traceh #include "ezport.h" #define jr_malloc_calls_TRACE 10 #define jr_malloc_trap_TRACE 11 #define jr_malloc_bounds_TRACE 12 #define jr_malloc_stats_TRACE 13 #define jr_malloc_trace_TRACE 14 #define jr_io_TRACE 20 #define jr_string_TRACE 21 #define jr_network_TRACE 22 #define jr_exceptions_TRACE 23 #define jr_locks_TRACE 24 #define jr_graphics_TRACE 30 #define jr_cgi_TRACE 31 #define jr_nfa_dfa_TRACE 32 #define jr_fcache_TRACE 33 #define jr_macro_preprocessor_TRACE 34 #define jr_build_update_TRACE 35 #define jr_http_TRACE 36 #define jr_matrix_TRACE 40 #define jr_matrix_regions_TRACE 41 #define jr_static_matrix_TRACE 42 #define g2c_TRACE 50 #define g2c_repair_TRACE 51 #define g2c_parser_TRACE 52 #define s2c_TRACE 53 #define otree_file_TRACE 60 #define otree_server_TRACE 61 #define otree_client_TRACE 62 #define otree_adapter_TRACE 63 #define jr_TRACE_NUM_VALUES 100 typedef char jr_trace_t; jr_EXTERN(jr_trace_t) jr_TraceValues[]; #define jr_set_trace(t) ( jr_check_trace_macro(t##_TRACE), \ jr_TraceValues[t##_TRACE] = 1 \ ) #define jr_rm_trace(t) (jr_TraceValues[t##_TRACE] = 0) #define jr_set_trace_level(t, level) ( jr_check_trace_macro(t##_TRACE), \ jr_TraceValues[t##_TRACE] |= 1 << ((level)-1) \ ) #ifdef NDEBUG #define jr_NO_TRACE #endif #ifdef jr_NO_TRACE /* * When compiled with an optimizing compiler conditional statements * using "if (jr_do_trace(category)" will be optimized out of the executable */ # define jr_do_trace(t) (0) # define jr_trace_level(t) (0) # define jr_max_trace_level(t) (0) # define jr_is_trace_at_level(t, level) (0) # define jr_has_trace(t, level) (0) #else # define jr_do_trace(t) (jr_TraceValues[t##_TRACE]) # define jr_trace_level(t) (jr_TraceValues[t##_TRACE]) # define jr_max_trace_level(t) jr_trace_bit (jr_TraceValues[t##_TRACE]) # define jr_is_trace_at_level(t, level) ((level) > 0 \ ? jr_TraceValues[t##_TRACE] >= (1 << ((level) - 1)) \ : jr_TraceValues[t##_TRACE] == 0) # define jr_has_trace(t, level) ((level) > 0 \ ? jr_TraceValues[t##_TRACE] & (1 << ((level) - 1)) \ : 0) #endif #ifdef compiler_has_ansi_support # define jr_check_trace_macro(t) (jr_check_trace(t, __FILE__, __LINE__)) #else # define jr_check_trace_macro(t) (jr_check_trace (0, 0, 0)) /* ** no quoting macro args under non-ansi C, so no checking possible */ #endif jr_EXTERN(void) jr_check_trace PROTO(( jr_int trace_num, const char * file_name, jr_int line_number )) ; jr_EXTERN(jr_int) jr_trace_bit (jr_int trace_value); #define jr_trace_foreach_level(t, k) \ for ((k)=1; (k) <= (jr_int) sizeof (jr_int) * 8; (k)++) \ if (jr_trace_level (t) & (1 << (k) - 1)) #endif
frankjas/libjr
libjr/llist/llistpfx.c
#include "project.h" void jr_LListSetContainers ( jr_LList * list, ...) { va_list arg_list; va_start (arg_list, list); jr_LListSetContainersFromVA_List (list, arg_list); va_end (arg_list); } void jr_LListSetContainersFromVA_List (list, arg_list) jr_LList * list; va_list arg_list; { jr_PrefixInfoType * prefix_array; jr_int prefix_size; jr_int needs_transform_fn = 0; prefix_array = jr_PrefixArrayCreateFromVA_List (arg_list, needs_transform_fn); prefix_size = jr_PrefixArrayInitPrefixes (prefix_array); jr_LListSetPrefixSize (list, prefix_size); jr_PrefixArrayDestroy (prefix_array); } void jr_LListTransformPrefix (list, el_ptr, magnitude, which_way, all_elements) jr_LList * list; void * el_ptr; unsigned jr_int magnitude; jr_int which_way; jr_int all_elements; { void * next_ptr; void * old_el_ptr; old_el_ptr = jr_UnTransformAListPtr (el_ptr, magnitude, which_way); if (old_el_ptr == jr_LListHeadPtr (list)) { jr_LListHeadPtr (list) = el_ptr; } if (old_el_ptr == jr_LListTailPtr (list)) { jr_LListTailPtr (list) = el_ptr; } if (all_elements) { /* * do the next pointer, or the head and tail pointers */ next_ptr = jr_LListNextElementPtr (list, el_ptr); if (next_ptr) { next_ptr = jr_TransformAListPtr (next_ptr, magnitude, which_way); jr_LListNextElementPtr (list, el_ptr) = next_ptr; } } else { /* * have to find reference to old element */ void * prev_ptr; prev_ptr = 0; jr_LListForEachElementPtr (list, next_ptr) { if (next_ptr == old_el_ptr) { if (prev_ptr) { jr_LListNextElementPtr (list, prev_ptr) = el_ptr; } break; } prev_ptr = next_ptr; } } } void jr_LListMakeNullElement (list, el_ptr) jr_LList * list; void * el_ptr; { jr_LListNextElementPtr (list, el_ptr) = 0; }
frankjas/libjr
libjr/syscalls/size.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include "jr/syscalls.h" size_t jr_FilePtrDiskSize(fp) FILE *fp ; { struct stat buf ; jr_int fd = fileno(fp) ; if (fstat(fd,&buf) != 0) { return(0) ; } return(buf.st_size) ; } size_t jr_FileDescDiskSize(fd) jr_int fd ; { struct stat buf ; if (fstat(fd,&buf) != 0) { return(0) ; } return(buf.st_size) ; } size_t jr_FileNameDiskSize(fn) const char * fn ; { struct stat buf ; if (stat(fn,&buf) != 0) { return(0) ; } return(buf.st_size) ; } off_t jr_FileDescBlockSize (fd) jr_int fd; { struct stat buf ; if (fstat(fd,&buf) != 0) { return(0) ; } return(buf.st_blksize) ; } /******************************************************* main(argc,argv) jr_int argc ; char **argv ; { off_t size ; FILE *fp ; argv++ ; if ((fp = fopen(*argv,"a")) == NULL) { printf("Cant append to %s\n",*argv) ; exit(1) ; } size = (off_t) fsize(fp) ; printf ("Size of %s is %d.\n",*argv, size); fseek(fp,0,0) ; fprintf(fp,"start") ; fseek(fp,(size - strlen("finish\n"))+1,0) ; fprintf(fp,"finish\n") ; printf("%s : munged.\n",*argv) ; } *******************************************************/
frankjas/libjr
libjr/missing/strrchr.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <string.h> /* This function is identical to 'rindex(str,c)' */ #ifdef missing_strrchr char *strrchr(str, chr) const char *str ; int chr ; { jr_int i = strlen(str) ; char *ptr = (char *) str + i ; for (; ptr >= str ; ptr--) { if (*ptr == chr) return(ptr) ; } return(0) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/misc/exn_proj.h
#ifndef __exn_proj_h___ #define __exn_proj_h___ #define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <string.h> #include "jr/malloc.h" #include "jr/trace.h" #include "jr/misc.h" #include "jr/vector.h" #include "jr/alist.h" #include "jr/exceptn.h" extern jr_ExceptionType * jr_ExceptionCreate PROTO ((char *error_buf)); extern void jr_ExceptionDestroy PROTO ((jr_ExceptionType * exception_ptr)); typedef struct { jr_AList jmp_buf_list [1]; unsigned core_dump : 1; } jr_ExceptionStack; extern jr_ExceptionStack *jr_ExceptionStackCreate PROTO ((void)); extern void jr_ExceptionStackInit PROTO (( jr_ExceptionStack * exception_stack )); extern void jr_ExceptionStackDestroy PROTO (( jr_ExceptionStack * exception_stack )); extern void jr_ExceptionStackUndo PROTO (( jr_ExceptionStack * exception_stack )); extern jr_ExceptionType * jr_ExceptionStackPush PROTO (( jr_ExceptionStack * exception_stack, jr_ExceptionType * exception_ptr )); extern jr_ExceptionStack * jr_ExceptionStackPop PROTO (( jr_ExceptionStack * exception_stack )); #endif
frankjas/libjr
libjr/missing/strnccmp.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <string.h> #include <ctype.h> #ifdef missing_strncasecmp int strncasecmp( const char * str1, const char * str2, size_t max_chars) { int c1; int c2; int k; int diff; for (k = 0; *str1 != 0 && *str2 != 0 && k < max_chars; str1++, str2++, k++) { c1 = toupper (*str1); c2 = toupper (*str2); diff = c1 - c2; if (diff != 0) return diff; } return *str1 - *str2; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/string/vquote.c
#include "ezport.h" #include <stdio.h> #include <string.h> #include "jr/malloc.h" #include "jr/misc.h" #include "jr/vector.h" #include "jr/string.h" jr_int jr_VectorizeWithQuotes (str, delimiters, white_space, quotes, vector, vector_size) const char * str ; const char * delimiters ; const char * white_space ; const char * quotes ; char ** vector ; jr_int vector_size ; { const char * begin ; char * arg ; jr_int length ; jr_int argc = 0 ; jr_int in_quote = 0; jr_int last_char = 0; jr_int quote_stack[64]; jr_int quote_stack_depth = sizeof( quote_stack) / sizeof( jr_int); /* * skip leading white space */ for (; *str && strchr(white_space, *str); str++) ; if (*str == 0) { vector[0] = 0; return(0) ; } begin = str ; length = 0 ; for ( ;; str++) { if ((*str == 0) || (strchr(delimiters, *str) && !in_quote)) { /* * hit the end of a word */ if (argc == (vector_size - 1)) { /* * If we have hit the last valid index (where a null should go) * then stick the remaining un-vectorized string into this slot * and return. */ vector[argc++] = (char *) begin ; return(argc) ; } else { /* * Since we remembered the beginning of the string * and have counted the length up to this position * we are ready to save the bytes from the beginning * of the last argument to the current position. * * Remove trailing white space */ const char * end; const char * quote_ptr; for (end = begin + length; end > begin; end--) { if (strchr (white_space, end[-1]) == 0) { break; } } length = end - begin; if ((quote_ptr = strchr( quotes, begin[0])) != 0 && begin[length - 1] == *quote_ptr) { /* ** 1-17-2012: the first char is a quote and there's ** a matching quote in the last char. Strip both and ** but leave leading/trailing white space. Why? Bad design ** and now backward compatibility. */ begin++; length -= 2; } arg = (char *) jr_malloc(length+1) ; strncpy(arg, begin, length) ; arg[length] = 0 ; vector[argc++] = arg ; } if (*str == 0) break ; /* * skip leading white space on next word * (*str is a delimiter) */ for (str++; *str && strchr(white_space, *str) ; str++) ; if (*str == 0) break ; begin = str ; length = 0 ; if (*str && strchr(delimiters, *str)) { str-- ; continue ; } } if (*str && strchr (quotes, *str) && last_char != '\\') { jr_int stack_index = in_quote; if (stack_index >= quote_stack_depth) { /* ** 1-17-2012: we can only store quote_stack_depth levels of quote nesting. ** If we excede that, then we don't properly match open/close pairs, e.g. ** a begin single quote may be closed by a double quote. */ stack_index = -1; } if (in_quote && (stack_index == -1 || quote_stack[stack_index - 1] == *str)) { in_quote --; } else { quote_stack[stack_index] = *str; in_quote ++; } } /* * \\" does not escape the " */ if (last_char == '\\') { last_char = 0; } else { last_char = *str; } /* * If the char is not a delimiter than it is * part of an argument, so increment the length * of that argument. */ length++ ; } vector[argc] = 0 ; return(argc) ; } const char ** jr_VectorCreateWithQuotes (str, delimiters, white_space, quotes) const char * str ; const char * delimiters ; const char * white_space ; const char * quotes ; { char ** new_vector; jr_int max_elem = 8; jr_int num_elem; new_vector = jr_malloc (max_elem * sizeof (char *)); new_vector[max_elem - 1] = (char *) str; num_elem = 0; while (1) { num_elem += jr_VectorizeWithQuotes ( str, delimiters, white_space, quotes, new_vector + num_elem, max_elem - num_elem ); if (num_elem == max_elem) { str = new_vector[max_elem - 1]; num_elem = max_elem - 1; max_elem *= 2; new_vector = jr_realloc (new_vector, max_elem * sizeof (char *)); } else { break; } } return (const char **) new_vector; }
frankjas/libjr
libjr/io/bufio_apr.c
#include "ezport.h" #include "jr/bufio.h" #include "jr/error.h" #include "jr/malloc.h" void jr_BufferedIoSetFileInfo( jr_BufferedIoType * buf_io, jr_file_t * file_info) { buf_io->file_info = file_info; if (buf_io->read_buffer) { jr_free( buf_io->read_buffer); } buf_io->read_buffer_length = 8192; buf_io->read_buffer = jr_malloc( buf_io->read_buffer_length); jr_BufferedIoSetRawReadFn( buf_io, jr_BufferedIoFileRead, buf_io); } jr_int jr_BufferedIoFileRead( void * raw_read_arg, unsigned jr_int max_data_length, const char ** data_ptr_ref, unsigned jr_int * data_length_ref, char * error_buf) { jr_BufferedIoType * buf_io = raw_read_arg; jr_int num_bytes; jr_int status; /* ** 11-29-2011: use jr_file_read() since fread() buffers, i.e. won't return ** until the buffer is full or EOF. */ status = jr_file_read( buf_io->file_info, (char *) buf_io->read_buffer, buf_io->read_buffer_length, error_buf ); if (status < 0) { jr_esprintf( error_buf, "read error: %s", error_buf); goto return_status; } else { num_bytes = status; } *data_ptr_ref = buf_io->read_buffer; *data_length_ref = num_bytes; status = 0; return_status : { } return status; } void jr_BufferedIoSetSocket( jr_BufferedIoType * buf_io, jr_socket_t * sock_info) { buf_io->sock_info = sock_info; if (buf_io->read_buffer) { jr_free( buf_io->read_buffer); } buf_io->read_buffer_length = 8192; buf_io->read_buffer = jr_malloc( buf_io->read_buffer_length); jr_BufferedIoSetRawReadFn( buf_io, jr_BufferedIoSocketRead, buf_io); } jr_int jr_BufferedIoSocketRead( void * raw_read_arg, unsigned jr_int max_data_length, const char ** data_ptr_ref, unsigned jr_int * data_length_ref, char * error_buf) { jr_BufferedIoType * buf_io = raw_read_arg; jr_int num_bytes; jr_int status; status = jr_socket_recv( buf_io->sock_info, (char *) buf_io->read_buffer, buf_io->read_buffer_length, error_buf ); if (status < 0) { goto return_status; } else { num_bytes = status; } *data_ptr_ref = buf_io->read_buffer; *data_length_ref = num_bytes; status = 0; return_status : { } return status; }
frankjas/libjr
libjr/syscalls/invkfilt.c
<reponame>frankjas/libjr<filename>libjr/syscalls/invkfilt.c #define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/wait.h> #include <string.h> #include <signal.h> #include "jr/string.h" #include "jr/alist.h" #include "jr/trace.h" #include "jr/malloc.h" #include "jr/syscalls.h" #include "jr/error.h" #define MAX_LINE 1024 char *jr_NewStringFilteredFromCommandVector (argv, input_to_filter_str, error_buf) char ** argv; const char * input_to_filter_str; char * error_buf; { const char * begin_ptr; jr_int i; jr_int line_length; jr_int nbytes; jr_int flags; jr_int wait_status; char output_buffer [MAX_LINE]; char * new_str; FILE * pipe_fps [2]; jr_int rfd; jr_int wfd; jr_AList output_string [1]; pid_t childs_pid; childs_pid = jr_Invoke2WayCommandVector (argv, pipe_fps, error_buf); if (childs_pid < 0) { jr_esprintf (error_buf, "couldn't spawn '%s': %s", argv[0], error_buf); return (0); } rfd = fileno (pipe_fps [1]); wfd = fileno (pipe_fps [0]); flags = fcntl (rfd, F_GETFL, 0); flags |= O_NDELAY; fcntl (rfd, F_SETFL, flags); jr_AListInit (output_string, sizeof (char)); for (begin_ptr = input_to_filter_str, i = 0; begin_ptr [i]; i++) { if (begin_ptr [i] == '\n') { line_length = i + 1; nbytes = write (wfd, (char *) begin_ptr, line_length); if (nbytes != line_length) { jr_esprintf (error_buf, "couldn't write(%s:%d, %p, %d) return of %d : %s", argv[0], wfd, begin_ptr, line_length, nbytes, strerror(errno) ); goto return_bad; } while (1) { nbytes = read (rfd, output_buffer, sizeof (output_buffer)); if (nbytes == -1) { if (errno == EWOULDBLOCK) break; /* non-posix errno */ if (errno == EAGAIN) break; jr_esprintf (error_buf, "couldn't read from '%s': %s", argv [0], strerror (errno) ); goto return_bad; } if (nbytes == 0) { break; } { jr_int i; for (i=0; i < nbytes; i++) { jr_AListNativeSetNewTail (output_string, output_buffer [i], char); } } } begin_ptr += line_length; i = -1; /* * so next time through the loop i will be 0 */ } } fclose (pipe_fps [1]); /* * send eof to command */ flags = fcntl (rfd, F_GETFL); flags &= ~O_NDELAY; fcntl (rfd, F_SETFL, flags); /* * set up blocking io to wait for eof */ while (1) { nbytes = read (rfd, output_buffer, sizeof (output_buffer)); if (nbytes == -1) { jr_esprintf (error_buf, "couldn't read from '%s': %s", argv [0], strerror (errno)); goto return_bad; } if (nbytes == 0) { break; } { jr_int i; for (i=0; i < nbytes; i++) { jr_AListNativeSetNewTail (output_string, output_buffer [i], char); } } } jr_AListNativeSetNewTail (output_string, 0, char); if (1) { new_str = jr_strdup (jr_AListHeadPtr (output_string)); } else return_bad : { kill (childs_pid, SIGKILL); new_str = 0; } jr_AListUndo (output_string); waitpid (childs_pid, &wait_status, 0); fclose (pipe_fps [0]); /* * Do this after waitpid() so the child won't get SIGPIPE */ if (WIFEXITED (wait_status) && WEXITSTATUS (wait_status) != 0) { if (new_str) { jr_free (new_str); } jr_esprintf (error_buf, "'%s' exited with bad status %d", argv[0], WEXITSTATUS (wait_status)); return (0); } if (WIFSIGNALED (wait_status) && WTERMSIG (wait_status) != SIGKILL) { if (new_str) { jr_free (new_str); } jr_esprintf (error_buf, "'%s' was terminated by a signal%s", argv[0], WIFCORE (wait_status) ? " and dumped core" : "" ); return (0); } return new_str; } #ifdef _test_filter_string void main (argc, argv) jr_int argc; char **argv; { char test_string [512]; char error_buf [512]; char *sed_string; jr_int status; jr_set_trace (jr_malloc_stats); sprintf (test_string, "hello there everyone\n"); sed_string = jr_FilterStringWithCommandVector (argv + 1, test_string, error_buf); if (sed_string == 0) { fprintf (stderr, "Couldn't filter the string: %.150s\n", error_buf); } else { printf ("Original string: '%s'\n", test_string); printf ("Filtered string: '%s'\n", sed_string); } jr_free (sed_string); jr_malloc_stats (stderr, "After UndoSedType"); } #endif
frankjas/libjr
libjr/avl_tree/avl_ins.c
<reponame>frankjas/libjr #include "project.h" void *jr_AVL_TreeSetNewElementWithSize(avl_tree, key_node, length) jr_AVL_Tree * avl_tree; const void * key_node ; jr_int length ; { void * new_node; new_node = jr_AVL_TreeNewElementPtrWithSize (avl_tree, key_node, length); if (new_node) { memcpy (new_node, key_node, length); } return new_node; } void *jr_AVL_TreeNewElementPtrWithSize(avl_tree, key_node, length) jr_AVL_Tree * avl_tree; const void * key_node ; jr_int length ; { void * new_node; jr_int status; new_node = jr_AVL_TreeAllocateElementWithSize (avl_tree, length); status = jr_AVL_TreeInsertElementUsingKey (avl_tree, new_node, key_node); if (status == -1) { jr_AVL_TreeFreeElement (avl_tree, new_node); return 0; } return new_node; } jr_int jr_AVL_TreeInsertElementUsingKey (avl_tree, new_node, key_node) jr_AVL_Tree * avl_tree; const void * new_node; const void * key_node; { void * path[jr_AVL_TREE_MAX_HEIGHT]; jr_int path_index; void * curr_node; jr_int comp_val = 0; /* to shutup 'unused' warning */ jr_int is_left_child; curr_node = avl_tree->root_node; for (path_index = 0; curr_node; path_index++) { path[path_index] = curr_node; comp_val = (*avl_tree->cmpfn) (key_node, curr_node, avl_tree->cmpfn_arg) ; if (comp_val == 0) return -1; if (comp_val < 0) { curr_node = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node); } else { curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node); } } /* * comp_val tells which side to put node on * * path [path_index - 1] contains the parent of new_node */ if (comp_val < 0) { is_left_child = 1; } else { is_left_child = 0; } jr_AVL_TreeAppendToPath (avl_tree, path, path_index, is_left_child, new_node); return 0; } void jr_AVL_TreeAppendToPath (avl_tree, path, path_length, is_left_child, new_node) jr_AVL_Tree * avl_tree; void * path[]; jr_int path_length; jr_int is_left_child; const void * new_node; { if (path_length > 0) { if (is_left_child) { jr_AVL_TreeLeftChildPtr (avl_tree, path [path_length - 1]) = (void *) new_node; } else { jr_AVL_TreeRightChildPtr (avl_tree, path [path_length - 1]) = (void *) new_node; } } else { avl_tree->root_node = (void *) new_node; } jr_AVL_TreeLeftChildPtr (avl_tree, new_node) = 0 ; jr_AVL_TreeRightChildPtr (avl_tree, new_node) = 0 ; jr_AVL_TreeElementHeight (avl_tree, new_node) = 0 ; if (jr_AVL_TreeMaintainsSize (avl_tree)) { jr_int i; jr_AVL_TreeSetSubTreeSize (avl_tree, new_node, 1); for (i=0; i < path_length; i++) { jr_AVL_TreeIncrementElementTreeSize (avl_tree, path[i]); } } jr_AVL_TreeBalancePath (avl_tree, path, path_length); /* * Update the height of the nodes by backing up the path. */ } void jr_AVL_TreeBalancePath (avl_tree, path, path_length) jr_AVL_Tree * avl_tree; void ** path; jr_int path_length; { void * right_child; void * left_child; jr_int left_height, right_height; jr_int max_child_height; jr_int path_index, diff; for (path_index = path_length - 1; path_index >= 0; path_index--) { right_child = jr_AVL_TreeRightChildPtr (avl_tree, path[path_index]); left_child = jr_AVL_TreeLeftChildPtr (avl_tree, path[path_index]); /* * get the heights of the children */ if (right_child) { right_height = jr_AVL_TreeElementHeight (avl_tree, right_child); } else { right_height = -1; } if (left_child) { left_height = jr_AVL_TreeElementHeight (avl_tree, left_child); } else { left_height = -1; } if (right_height < left_height) { max_child_height = left_height; diff = left_height - right_height; } else { max_child_height = right_height; diff = right_height - left_height; } if (diff == 2) { if (path_index - 1 < 0) { /* * the current node is the root * the 0 argument tells jr_AVL_TreeBalanceElement this * is the case */ jr_AVL_TreeBalanceElement (avl_tree, path[path_index], 0); } else { jr_AVL_TreeBalanceElement (avl_tree, path[path_index], path[path_index - 1]); } /* we are guaranteed that the curr node is * balanced and its height is no greater than it * was prior to the insertion, so we don't * have to back any further down the path */ break; } /* * no balancing needed, but we may have to propogate * some height information back to the parent */ if (jr_AVL_TreeElementHeight (avl_tree, path[path_index]) == max_child_height + 1) { /* * We know that before the insertion this statement * was true. However after an insertion one * of the children was increased by one. In this * case it was the "shorter" child so we didn't * change the height of this node. */ break; } /* * Continue in the loop, i.e. look at the parent * since we may end up unbalancing the tree farther back. */ jr_AVL_TreeElementHeight (avl_tree, path[path_index]) = max_child_height + 1; } } void jr_AVL_TreeBalanceElement (avl_tree, curr_node, parent_node) jr_AVL_Tree * avl_tree; void * curr_node; void * parent_node; { void * right_child; void * left_child; jr_int right_height; jr_int left_height; right_child = jr_AVL_TreeRightChildPtr (avl_tree, curr_node); left_child = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node); /* * initialize height information */ if (right_child) { right_height = jr_AVL_TreeElementHeight (avl_tree, right_child); } else { right_height = -1; } if (left_child) { left_height = jr_AVL_TreeElementHeight (avl_tree, left_child); } else { left_height = -1; } if (right_height > left_height) { void * right_grand_child; void * left_grand_child; jr_int right_grand_height; jr_int left_grand_height; right_grand_child = jr_AVL_TreeRightChildPtr (avl_tree, right_child); left_grand_child = jr_AVL_TreeLeftChildPtr (avl_tree, right_child); if (right_grand_child) { right_grand_height = jr_AVL_TreeElementHeight (avl_tree, right_grand_child); } else { right_grand_height = -1; } if (left_grand_child) { left_grand_height = jr_AVL_TreeElementHeight (avl_tree, left_grand_child); } else { left_grand_height = -1; } if (right_grand_height > left_grand_height) { /* * Single rotation: * right_child becomes curr_node with * curr_node and right_grand as left, right children. * curr_node has left_child and left_grand as left, right children. */ /* * make right_child the new curr_node */ if (parent_node) { if (jr_AVL_TreeRightChildPtr (avl_tree, parent_node) == curr_node) { jr_AVL_TreeRightChildPtr (avl_tree, parent_node) = right_child; } else { jr_AVL_TreeLeftChildPtr (avl_tree, parent_node) = right_child; } } else { avl_tree->root_node = right_child; } jr_AVL_TreeLeftChildPtr (avl_tree, right_child) = curr_node; jr_AVL_TreeRightChildPtr (avl_tree, curr_node) = left_grand_child; /* * adjust the heights */ jr_AVL_TreeElementHeight (avl_tree, curr_node) = left_height + 1; jr_AVL_TreeElementHeight (avl_tree, right_child) = right_grand_height + 1; if (jr_AVL_TreeMaintainsSize (avl_tree)) { /* order of update matters */ jr_AVL_TreeElementUpdateTreeSize (avl_tree, curr_node); jr_AVL_TreeElementUpdateTreeSize (avl_tree, right_child); } } else { /* * left_grand_height > right_grand_height * Double rotation (see diagram). * left_grand_child becomes curr_node. * The order of assignments below is important. */ if (parent_node) { if (jr_AVL_TreeRightChildPtr (avl_tree, parent_node) == curr_node) { jr_AVL_TreeRightChildPtr (avl_tree, parent_node) = left_grand_child; } else { jr_AVL_TreeLeftChildPtr (avl_tree, parent_node) = left_grand_child; } } else { avl_tree->root_node = left_grand_child; } jr_AVL_TreeRightChildPtr (avl_tree, curr_node) = jr_AVL_TreeLeftChildPtr (avl_tree, left_grand_child); jr_AVL_TreeElementHeight (avl_tree, curr_node) = left_height + 1; jr_AVL_TreeLeftChildPtr (avl_tree, right_child) = jr_AVL_TreeRightChildPtr (avl_tree, left_grand_child); jr_AVL_TreeElementHeight (avl_tree, right_child) = right_grand_height + 1; jr_AVL_TreeLeftChildPtr (avl_tree, left_grand_child) = curr_node; jr_AVL_TreeRightChildPtr (avl_tree, left_grand_child) = right_child; jr_AVL_TreeElementHeight (avl_tree, left_grand_child) = jr_AVL_TreeElementHeight (avl_tree, curr_node) + 1; if (jr_AVL_TreeMaintainsSize (avl_tree)) { jr_AVL_TreeElementUpdateTreeSize (avl_tree, curr_node); jr_AVL_TreeElementUpdateTreeSize (avl_tree, right_child); jr_AVL_TreeElementUpdateTreeSize (avl_tree, left_grand_child); } } } else { /* left_height > right_height */ void * right_grand_child; void * left_grand_child; jr_int right_grand_height; jr_int left_grand_height; left_grand_child = jr_AVL_TreeLeftChildPtr (avl_tree, left_child); right_grand_child = jr_AVL_TreeRightChildPtr (avl_tree, left_child); if (right_grand_child) { right_grand_height = jr_AVL_TreeElementHeight (avl_tree, right_grand_child); } else { right_grand_height = -1; } if (left_grand_child) { left_grand_height = jr_AVL_TreeElementHeight (avl_tree, left_grand_child); } else { left_grand_height = -1; } if (left_grand_height > right_grand_height) { /* * Single rotation. * left_child becomes the curr_node with * left_grand_child, currnode as left and right children. * curr_node has right_grand_child and right_child as left and right children. */ /* * make left_child the new curr_node */ if (parent_node) { if (jr_AVL_TreeRightChildPtr (avl_tree, parent_node) == curr_node) { jr_AVL_TreeRightChildPtr (avl_tree, parent_node) = left_child; } else { jr_AVL_TreeLeftChildPtr (avl_tree, parent_node) = left_child; } } else { avl_tree->root_node = left_child; } jr_AVL_TreeRightChildPtr (avl_tree, left_child) = curr_node; jr_AVL_TreeLeftChildPtr (avl_tree, curr_node) = right_grand_child; jr_AVL_TreeElementHeight (avl_tree, curr_node) = right_height + 1; jr_AVL_TreeElementHeight (avl_tree, left_child) = left_grand_height+1; if (jr_AVL_TreeMaintainsSize (avl_tree)) { /* order of update matters */ jr_AVL_TreeElementUpdateTreeSize (avl_tree, curr_node); jr_AVL_TreeElementUpdateTreeSize (avl_tree, left_child); } } else { /* * right_grand_height > left_grand_height * Double rotation (see diagram). * right_grand_child becomes curr_node. * The order of assignments below is important. */ if (parent_node) { if (jr_AVL_TreeRightChildPtr (avl_tree, parent_node) == curr_node) { jr_AVL_TreeRightChildPtr (avl_tree, parent_node) = right_grand_child; } else { jr_AVL_TreeLeftChildPtr (avl_tree, parent_node) = right_grand_child; } } else { avl_tree->root_node = right_grand_child; } jr_AVL_TreeLeftChildPtr (avl_tree, curr_node) = jr_AVL_TreeRightChildPtr (avl_tree, right_grand_child); jr_AVL_TreeElementHeight (avl_tree, curr_node) = right_height + 1; jr_AVL_TreeRightChildPtr (avl_tree, left_child) = jr_AVL_TreeLeftChildPtr (avl_tree, right_grand_child); jr_AVL_TreeElementHeight (avl_tree, left_child) = left_grand_height + 1; jr_AVL_TreeRightChildPtr (avl_tree, right_grand_child) = curr_node; jr_AVL_TreeLeftChildPtr (avl_tree, right_grand_child) = left_child; jr_AVL_TreeElementHeight (avl_tree, right_grand_child) = jr_AVL_TreeElementHeight (avl_tree, curr_node) + 1; if (jr_AVL_TreeMaintainsSize (avl_tree)) { jr_AVL_TreeElementUpdateTreeSize (avl_tree, curr_node); jr_AVL_TreeElementUpdateTreeSize (avl_tree, left_child); jr_AVL_TreeElementUpdateTreeSize (avl_tree, right_grand_child); } } } } void jr_AVL_TreeElementUpdateTreeSize (avl_tree, node_ptr) jr_AVL_Tree * avl_tree; void * node_ptr; { void * left_child = jr_AVL_TreeLeftChildPtr (avl_tree, node_ptr); void * right_child = jr_AVL_TreeRightChildPtr (avl_tree, node_ptr); jr_int tree_size = 1; if (left_child) { tree_size += jr_AVL_TreeSubTreeSize (avl_tree, left_child); } if (right_child) { tree_size += jr_AVL_TreeSubTreeSize (avl_tree, right_child); } jr_AVL_TreeSetSubTreeSize (avl_tree, node_ptr, tree_size); }
frankjas/libjr
include/jr/inetlib.h
#ifndef __JR_INETLIB_H__ #define __JR_INETLIB_H__ #include "ezport.h" #include <sys/types.h> #ifdef ostype_winnt # include <winsock2.h> #else # include <sys/socket.h> # include <netinet/in.h> # include <arpa/inet.h> #endif #define jr_RCV_DISALLOW 0 /* shutdown modes */ #define jr_SND_DISALLOW 1 /* shutdown modes */ #define jr_ALL_DISALLOW 2 /* shutdown modes */ #define jr_MAX_IOVLEN 15 /* * 16 is the documented maximum, but 15 is the largest * size that doesn't generate an error with sendmsg */ #define jr_RANDOM_PORT 0 #define jr_CLASS_A_MASK 0xff000000 #define jr_CLASS_B_MASK 0xffff0000 #define jr_CLASS_C_MASK 0xffffff00 #define jr_INET_SYSTEM_ERROR (jr_MIN_ERROR - 1) #define jr_INET_TIMED_OUT (jr_MIN_ERROR - 2) #define jr_INET_HOST_NOT_FOUND (jr_MIN_ERROR - 3) #define jr_INET_BAD_ADDRESS_FAMILY (jr_MIN_ERROR - 4) #define jr_INET_CONNECTION_REFUSED (jr_MIN_ERROR - 5) #define jr_INET_UNREACHABLE (jr_MIN_ERROR - 6) #define jr_INET_MIN_ERROR jr_INET_UNREACHABLE extern jr_int jr_InetAddressInit PROTO (( struct sockaddr_in * sa, const char * hostname, jr_int portnum, char * error_buf )); extern char * jr_InetGetHostErrorString PROTO (( jr_int gethost_errno )); extern jr_int jr_InetGetHostErrorTranslate PROTO (( jr_int gethost_errno )); extern jr_int jr_InetGetPortNumber PROTO (( jr_int socket_fd, char * opt_error_buf )); extern jr_int jr_InetConnectToService PROTO (( const char * hostname, jr_int portnum, char * error_buf )); extern jr_int jr_InetConnectToServiceWithTimeOut PROTO (( const char * hostname, jr_int portnum, jr_int time_out_seconds, char * error_buf )); extern jr_int jr_InetOfferService PROTO (( jr_int socket_type, struct sockaddr_in * socket_addr_ptr, char * error_buf )); extern jr_int jr_InetGetDGramSocket PROTO (( const char * localhostname, jr_int port_number, char * error_buf )); extern char * jr_InetAddressToString PROTO (( struct sockaddr_in * in_addr, char * string )); extern char * jr_InetNumberToString PROTO (( unsigned long ip_number )); extern jr_int jr_sockaddr_in_cmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); #define jr_SOCKET_READ_ERROR -1 /* errno contains read() error */ #define jr_SOCKET_READ_NO_SPACE -2 /* buffer filled up before newline */ /* in this case, buffer contains a string */ extern jr_int jr_socket_readlines PROTO (( jr_int socket_rfd, char * line_buffer, jr_int line_buffer_size )); /* * Reads what's available, blocks if newline not seen. */ /******** RPC Interface ********/ #define jr_RPC_PROTO_UDP 1 #define jr_RPC_PROTO_TCP 2 #define jr_RPC_MIN_PROGRAM_NUMBER 0x20000000 extern jr_int jr_RPC_RegisterPort ( jr_int program_number, jr_int version_number, jr_int protocol, jr_int port_number, char * error_buf); extern jr_int jr_RPC_UnRegisterPort ( jr_int program_number, jr_int version_number, char * error_buf); extern jr_int jr_RPC_LookupPort ( const char * host_name, jr_int program_number, jr_int version_number, jr_int protocol, char * error_buf); #endif
frankjas/libjr
libjr/string/esctoctl.c
<reponame>frankjas/libjr #include "ezport.h" #include <stdio.h> #include <ctype.h> #include <string.h> #include "jr/string.h" /***************************************************** This module provides routines for manipulating escaped characters in strings. Escaped characters are those which are preceded with a backslash. The recognized jr_EscapedCharsToControlChars are: \a = ??? \b = backspace \f = formfeed \n = newline \t = tab \v = vertical tab \\ = a single backslash \" an embedded double quote \' an embedded single quote a backslash before any other character is interpreted as just being that character. jr_EscapedCharsToControlChars(s) char *s ; translates the characters in 's' to be their escaped equivalents jr_EndsWithOddBackslashes(s) char *s ; determines if the string argument ends in an odd number of backslashes. This is useful in the context of the scanner, where it is necessary to know whether to continue reading a string constant (in the case where an odd number of back slashes occur before a double quote) *************************************************************/ void jr_EscapedCharsToControlChars (s) char *s ; { char *t=s, *f=s ; for(; *f; f++, t++) { if (*f == '\\') { f++; switch(*f) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { jr_int hexadecimal; sscanf (f, "%x", &hexadecimal); *t = hexadecimal; for (; *f; f++) { if (! isdigit(*f)) { f-- ; /* accomodate for the outer loop increment */ break ; } } continue; } case '0': { jr_int octal; sscanf (f, "%o", &octal); *t = octal; for (; *f; f++) { if (! isdigit(*f)) { f-- ; /* accomodate for the outer loop increment */ break ; } } continue; } case 'a': *t = '\a' ; continue ; case 'b': *t = '\b' ; continue ; case 'f': *t = '\f' ; continue ; case 'n': *t = '\n' ; continue ; case 'r': *t = '\r' ; continue ; case 't': *t = '\t' ; continue ; case 'v': *t = '\v' ; continue ; default: *t = *f ; continue ; } } else *t = *f ; } *t = '\0' ; } jr_int jr_EndsWithOddBackslashes(s) const char *s ; { const char * tp ; jr_int len = (jr_int) strlen(s) ; jr_int occur = 0 ; for (tp=(s+len); len; len--) { if (*(--tp) == '\\') occur++ ; else break ; } return(occur % 2) ; } /* void main() { char result[128] ; char * original = "\\f\\fline 1\\012\\00002hello 12345 there 6" ; strcpy(result, original) ; jr_EscapedCharsToControlChars(result) ; fprintf(stdout, "jr_EscapedCharsToControlChars('%s') == %s\n", original, result ) ; } */
frankjas/libjr
libjr/llist/project.h
<gh_stars>0 #ifndef __project_h_ #define __project_h_ #define _POSIX_SOURCE 1 #include "ezport.h" #include <assert.h> #include <stdarg.h> #include "jr/llist.h" #include "jr/malloc.h" #include "jr/alist.h" #include "jr/prefix.h" #endif
frankjas/libjr
libjr/syscalls/jr_thread.c
<filename>libjr/syscalls/jr_thread.c #include "jr_apr.h" #include <apr-1/apr_thread_proc.h> void jr_thread_init ( jr_thread_t * thread_ptr) { memset (thread_ptr, 0, sizeof (jr_thread_t)); jr_apr_initialize(); } void jr_thread_undo ( jr_thread_t * thread_ptr) { if (thread_ptr->apr_thread_ptr) { jr_thread_detach( thread_ptr, 0); } else if (thread_ptr->apr_pool_ptr) { apr_pool_destroy (thread_ptr->apr_pool_ptr); thread_ptr->apr_pool_ptr = 0; } } static void * APR_THREAD_FUNC jr_thread_fn( apr_thread_t * apr_thread_ptr, void * data_ptr) { jr_thread_t * thread_ptr = data_ptr; thread_ptr->thread_fn( thread_ptr, thread_ptr->arg_ptr); return 0; } jr_int jr_thread_spawn ( jr_thread_t * thread_ptr, void (*thread_fn)( jr_thread_t * thread_ptr, void * arg_ptr ), void * arg_ptr, char * error_buf) { jr_int status; if (thread_ptr->apr_pool_ptr == 0) { status = apr_pool_create ((apr_pool_t **) &thread_ptr->apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } thread_ptr->thread_fn = thread_fn; thread_ptr->arg_ptr = arg_ptr; status = apr_thread_create ( (apr_thread_t **) &thread_ptr->apr_thread_ptr, 0, jr_thread_fn, thread_ptr, (apr_pool_t *) thread_ptr->apr_pool_ptr ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status: { } return status; } jr_int jr_thread_detach ( jr_thread_t * thread_ptr, char * error_buf) { apr_status_t status; status = apr_thread_detach( (apr_thread_t *) thread_ptr->apr_thread_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status: { } return status; } void jr_thread_exit( jr_thread_t * thread_ptr, jr_int exit_status) { apr_thread_exit( thread_ptr->apr_thread_ptr, exit_status); thread_ptr->apr_thread_ptr = 0; } jr_int jr_thread_wait( jr_thread_t * thread_ptr, jr_int * exit_status_ref, char * error_buf) { apr_status_t exit_status; apr_status_t status; status = apr_thread_join( &exit_status, (apr_thread_t *) thread_ptr->apr_thread_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } thread_ptr->apr_thread_ptr = 0; status = 0; *exit_status_ref = exit_status; return_status: { } return status; }
frankjas/libjr
libjr/missing/strccmp.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <string.h> #include <ctype.h> #ifdef missing_strcasecmp int strcasecmp (str1, str2) const char * str1; const char * str2; { int c1; int c2; int diff; for (; *str1 != 0 && *str2 != 0; str1++, str2++) { c1 = toupper (*str1); c2 = toupper (*str2); diff = c1 - c2; if (diff != 0) return diff; } return *str1 - *str2; } #else #ifdef ostype_macosx #pragma GCC diagnostic ignored "-Winfinite-recursion" #endif static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/syscalls/envtilde.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <pwd.h> #include <errno.h> #include "jr/vector.h" #include "jr/malloc.h" #include "jr/string.h" char * jr_NewStringFromDollarAndTildeExpansion(word_arg) const char * word_arg ; { char directory_name[2048] ; const char * temp_word_value = 0 ; if (*word_arg == '$') { const char * environment_variable_name = word_arg + 1 ; if ((strcmp(environment_variable_name, "CWD") == 0) || (strcmp(environment_variable_name, "PWD") == 0)) { getcwd(directory_name, sizeof(directory_name)) ; directory_name[sizeof(directory_name)-1] = 0 ; temp_word_value = directory_name ; } else { temp_word_value = getenv(environment_variable_name) ; } } else if (*word_arg == '~') { const char * username = word_arg + 1 ; struct passwd * password_info ; if (*username == 0) { password_info = getpwuid(getuid()) ; } else { password_info = getpwnam(username) ; } if (password_info != 0) { temp_word_value = password_info->pw_dir ; /* home directory of username or self */ } } /* allocate result if necessary and return */ { char * new_word_result ; if (temp_word_value != 0) { new_word_result = jr_strdup(temp_word_value) ; } else { errno = 0 ; new_word_result = 0 ; } return(new_word_result) ; } } jr_int jr_PathStringCopyWithDollarAndTildeExpansion(target_str, source_str) char * target_str ; const char * source_str ; { if (strcmp(source_str, "/") == 0) { strcpy(target_str, source_str) ; return(0) ; } else { char * fullpathv[128] ; char * cur_component ; jr_int maxdirs = sizeof(fullpathv) / sizeof(char *) ; jr_int i, n ; jr_int last_char ; jr_int first_char ; { char * end_ptr = strchr(source_str, 0) ; last_char = end_ptr[-1] ; first_char = source_str[0] ; } n = jr_VectorizeIntoWords(source_str, "/", fullpathv, maxdirs) ; if (n == maxdirs) { for (i=0; i < n; i++) { jr_free(fullpathv[i]) ; } errno = 0 ; return(-1) ; } for (i=0 ; i < n; i++) { cur_component = fullpathv[i] ; if ((*cur_component == '$') || (*cur_component == '~')) { char * new_component ; new_component = jr_NewStringFromDollarAndTildeExpansion(fullpathv[i]) ; if (new_component == 0) { jr_VectorUndo(fullpathv) ; return(-1) ; } jr_free(cur_component) ; fullpathv[i] = new_component ; } } if (first_char == '/') { strcpy(target_str, "/") ; } else { *target_str = 0 ; } for (i=0; i < n; i++) { strcat(target_str, fullpathv[i]) ; jr_free(fullpathv[i]) ; if (fullpathv[i+1]) { strcat(target_str, "/") ; } } if (last_char == '/') { char * end_ptr = strchr(target_str,0) ; if (end_ptr[-1] != '/') { strcat(target_str, "/") ; } } } return(0) ; }
frankjas/libjr
libjr/avl_tree/avl_tree.c
#include "project.h" jr_AVL_Tree *jr_AVL_TreeCreate (element_size, cmpfn) jr_int element_size; jr_int (*cmpfn)() ; { jr_AVL_Tree * avl_tree; avl_tree = jr_malloc (sizeof(jr_AVL_Tree)); jr_AVL_TreeInit (avl_tree, element_size, cmpfn); return (avl_tree); } void jr_AVL_TreeInit (avl_tree, element_size, cmpfn) jr_AVL_Tree * avl_tree; jr_int element_size; jr_int (*cmpfn)() ; { avl_tree->element_size = element_size; avl_tree->cmpfn = cmpfn; avl_tree->cmpfn_arg = 0; avl_tree->root_node = 0; # ifdef has_jr_avl_tree_with_prefix avl_tree->prefix_size = 0; avl_tree->allocates_elements = 0; { static jr_int added_prefix_info = 0; if (!added_prefix_info) { added_prefix_info = 1; jr_PrefixAddContainerType ( "jr_AVL_Tree", jr_AVL_TreeElementPrefixSize, jr_AVL_TreeTransformPrefix, jr_AVL_TreeSetPrefixSize, 0 ); } } if (cmpfn == jr_AVL_TreeIndexedCmp) { avl_tree->maintains_size = 1; } # endif } void jr_AVL_TreeDestroy (avl_tree) jr_AVL_Tree * avl_tree; { jr_AVL_TreeUndo (avl_tree); jr_free (avl_tree); } /*| begin jr_AVL_TreeUndo_decl |*/ void jr_AVL_TreeUndo (avl_tree) jr_AVL_Tree * avl_tree; { jr_AVL_TreeEmpty (avl_tree); } void jr_AVL_TreeEmpty (avl_tree) jr_AVL_Tree * avl_tree; { if (avl_tree->root_node) { jr_AVL_TreeTraverseFree (avl_tree, avl_tree->root_node); } avl_tree->root_node = 0; } void jr_AVL_TreeTraverseFree (avl_tree, curr_node) jr_AVL_Tree * avl_tree; void * curr_node; { void * right_child ; void * left_child ; /*| end jr_AVL_TreeUndo_decl |*/ if (! jr_AVL_TreeAllocatesElements (avl_tree)) { return; } /*| begin jr_AVL_TreeUndo_decl |*/ left_child = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node); if (left_child) { jr_AVL_TreeTraverseFree (avl_tree, left_child); } right_child = jr_AVL_TreeRightChildPtr (avl_tree, curr_node); if (right_child) { jr_AVL_TreeTraverseFree (avl_tree, right_child); } jr_AVL_TreeFreeElement (avl_tree, curr_node); } /*| end jr_AVL_TreeUndo_decl |*/ #ifdef has_jr_avl_tree_with_prefix jr_int jr_AVL_TreeElementPrefixSize (avl_tree) jr_AVL_Tree * avl_tree; { jr_int element_prefix_size = sizeof (jr_AVL_TreeElementStruct); if (avl_tree && avl_tree->maintains_size) { element_prefix_size += sizeof (jr_AVL_TreeSizeStruct); } return element_prefix_size; } void jr_AVL_TreeSetPrefixSize (avl_tree, prefix_size) jr_AVL_Tree * avl_tree; jr_int prefix_size; { assert (jr_AVL_TreeIsEmpty (avl_tree)); avl_tree->prefix_size = prefix_size; } #endif void *jr_AVL_TreeAllocateElementWithSize (avl_tree, length) jr_AVL_Tree * avl_tree; jr_int length ; { char * new_node; jr_int element_prefix_size = 0; #ifdef has_jr_avl_tree_with_prefix avl_tree->allocates_elements = 1; element_prefix_size += jr_AVL_TreePrefixSize (avl_tree); if (avl_tree->maintains_size) { element_prefix_size += sizeof (jr_AVL_TreeSizeStruct); } #endif element_prefix_size += sizeof (jr_AVL_TreeElementStruct); new_node = jr_malloc (element_prefix_size + length) ; new_node += element_prefix_size; return new_node; } void jr_AVL_TreeFreeElement (avl_tree, node_ptr) jr_AVL_Tree * avl_tree; void * node_ptr; { jr_int element_prefix_size = 0; #ifdef has_jr_avl_tree_with_prefix element_prefix_size += jr_AVL_TreePrefixSize (avl_tree); if (avl_tree->maintains_size) { element_prefix_size += sizeof (jr_AVL_TreeSizeStruct); } #endif element_prefix_size += sizeof (jr_AVL_TreeElementStruct); jr_free ((char *) (node_ptr) - element_prefix_size); } /* * For use within the debugger */ static jr_AVL_TreeElementStruct *_jr_AVL_TreeElementPre (avl_tree, node_ptr) jr_AVL_Tree * avl_tree; void * node_ptr; { if (0) { _jr_AVL_TreeElementPre (avl_tree); } return jr_AVL_ElementInfoPtrWithPrefix (node_ptr, jr_AVL_TreePrefixSize (avl_tree)); } static void *_jr_AVL_TreeLeftChildPtr (avl_tree, node_ptr) jr_AVL_Tree * avl_tree; void * node_ptr; { if (0) { _jr_AVL_TreeLeftChildPtr (avl_tree, node_ptr); } return jr_AVL_TreeLeftChildPtr (avl_tree, node_ptr); } static void *_jr_AVL_TreeRightChildPtr (avl_tree, node_ptr) jr_AVL_Tree * avl_tree; void * node_ptr; { if (0) { _jr_AVL_TreeRightChildPtr (avl_tree, node_ptr); } return jr_AVL_TreeRightChildPtr (avl_tree, node_ptr); } static jr_int _jr_AVL_TreeSubTreeSize (avl_tree, node_ptr) jr_AVL_Tree * avl_tree; void * node_ptr; { if (0) { _jr_AVL_TreeSubTreeSize (avl_tree, node_ptr); } return jr_AVL_TreeSubTreeSize (avl_tree, node_ptr); }
frankjas/libjr
libjr/syscalls/jr_poll.c
#include "jr_poll.h" void jr_poll_init ( jr_poll_t * poll_ptr) { memset (poll_ptr, 0, sizeof (jr_poll_t)); jr_apr_initialize(); jr_HTableInit ( poll_ptr->event_table, sizeof (jr_pollevent_t *), jr_pollevent_ptr_hash, jr_pollevent_ptr_cmp ); jr_DListInit (poll_ptr->event_list, sizeof (jr_pollevent_t)); jr_AListInit (poll_ptr->result_list, sizeof (jr_pollevent_t)); } void jr_poll_undo ( jr_poll_t * poll_ptr) { jr_pollevent_t * event_ptr; char error_buf[jr_ERROR_LEN]; jr_HTableUndo (poll_ptr->event_table); jr_DListForEachElementPtr (poll_ptr->event_list, event_ptr) { event_ptr->io_style_ready = jr_POLL_CLOSE; jr_poll_call_handler (poll_ptr, event_ptr, error_buf); jr_pollevent_undo (event_ptr); } jr_DListUndo (poll_ptr->event_list); jr_AListUndo (poll_ptr->result_list); if (poll_ptr->apr_pollset_ptr) { apr_pollset_destroy (poll_ptr->apr_pollset_ptr); } if (poll_ptr->apr_pool_ptr) { apr_pool_destroy (poll_ptr->apr_pool_ptr); } } jr_int jr_poll_add_generic ( jr_poll_t * poll_ptr, void * generic_io_ptr, jr_int poll_flags, jr_int (*opt_handler_fn) ( void * data_ptr, jr_poll_t * poll_ptr, void * generic_io_ptr, jr_int is_style_ready, char * error_buf ), void * opt_handler_data_ptr, char * error_buf) { jr_pollevent_t * event_ptr; jr_int status; if (poll_ptr->apr_pool_ptr == 0) { status = apr_pool_create ((apr_pool_t **) &poll_ptr->apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } if (poll_ptr->apr_pollset_ptr == 0) { unsigned jr_int pollset_flags = 0; if (jr_poll_can_wakeup( poll_ptr)) { pollset_flags |= APR_POLLSET_WAKEABLE; } status = apr_pollset_create ( (apr_pollset_t **) &poll_ptr->apr_pollset_ptr, MIN_APR_POLLSET_SIZE, poll_ptr->apr_pool_ptr, pollset_flags ); if (status != 0) { jr_esprintf (error_buf, "couldn't create apr_pollset_t: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } poll_ptr->max_descriptors = MIN_APR_POLLSET_SIZE; } if (poll_ptr->num_descriptors >= poll_ptr->max_descriptors) { status = jr_poll_increase_capacity (poll_ptr, poll_ptr->num_descriptors + 1, error_buf); if (status != 0) { goto return_status; } } event_ptr = jr_poll_get_new_event ( poll_ptr, generic_io_ptr, poll_flags, opt_handler_fn, opt_handler_data_ptr ); if (event_ptr == 0) { jr_esprintf (error_buf, "already exists"); status = jr_IS_FOUND_ERROR; goto return_status; } status = jr_pollevent_add_to_pollset ( event_ptr, poll_ptr->apr_pollset_ptr, error_buf ); if (status != 0) { goto return_status; } poll_ptr->num_descriptors++; status = 0; return_status : { } return status; } jr_int jr_poll_add_socket ( jr_poll_t * poll_ptr, jr_socket_t * socket_ptr, jr_int poll_flags, jr_int (*opt_handler_fn) ( void * data_ptr, jr_poll_t * poll_ptr, jr_socket_t * socket_ptr, jr_int is_style_ready, char * error_buf ), void * opt_handler_data_ptr, char * error_buf) { jr_int status; status = jr_poll_add_generic ( poll_ptr, socket_ptr, poll_flags | jr_POLL_IS_SOCKET, (jr_poll_handler_fn_t) opt_handler_fn, opt_handler_data_ptr, error_buf ); return status; } jr_int jr_poll_add_file ( jr_poll_t * poll_ptr, jr_file_t * file_ptr, jr_int poll_flags, jr_int (*opt_handler_fn) ( void * data_ptr, jr_poll_t * poll_ptr, jr_file_t * file_ptr, jr_int is_style_ready, char * error_buf ), void * opt_handler_data_ptr, char * error_buf) { jr_int status; status = jr_poll_add_generic ( poll_ptr, file_ptr, poll_flags | jr_POLL_IS_FILE, (jr_poll_handler_fn_t) opt_handler_fn, opt_handler_data_ptr, error_buf ); return status; } void jr_poll_delete_generic ( jr_poll_t * poll_ptr, void * generic_io_ptr, jr_int poll_flags) { apr_pollfd_t apr_pollfd; jr_poll_delete_event (poll_ptr, generic_io_ptr, poll_flags); if (poll_ptr->apr_pollset_ptr) { memset (&apr_pollfd, 0, sizeof (apr_pollfd_t)); if (poll_flags & jr_POLL_IS_SOCKET) { apr_pollfd.desc_type = APR_POLL_SOCKET; apr_pollfd.desc.s = jr_socket_apr_ptr ((jr_socket_t *) generic_io_ptr); } if (poll_flags & jr_POLL_IS_FILE) { apr_pollfd.desc_type = APR_POLL_FILE; apr_pollfd.desc.f = jr_file_apr_ptr ((jr_file_t *) generic_io_ptr); } apr_pollset_remove (poll_ptr->apr_pollset_ptr, &apr_pollfd); /* ** 2/27/07: Only returns success or not-found, doesn't distinguish between READ/WRITE */ } } void jr_poll_delete_socket ( jr_poll_t * poll_ptr, jr_socket_t * socket_ptr) { jr_poll_delete_generic (poll_ptr, socket_ptr, jr_POLL_IS_SOCKET); } void jr_poll_delete_file ( jr_poll_t * poll_ptr, jr_file_t * file_ptr) { jr_poll_delete_generic (poll_ptr, file_ptr, jr_POLL_IS_FILE); } jr_int jr_poll_increase_capacity ( jr_poll_t * poll_ptr, jr_int new_size, char * error_buf) { apr_pollset_t * new_pollset_ptr = 0; unsigned jr_int poll_flags = 0; jr_pollevent_t * event_ptr; jr_int status; if (new_size < poll_ptr->max_descriptors) { return 0; } if (new_size < 2 * poll_ptr->max_descriptors) { new_size = 2 * poll_ptr->max_descriptors; } if (jr_poll_can_wakeup( poll_ptr)) { poll_flags |= APR_POLLSET_WAKEABLE; } status = apr_pollset_create ( (apr_pollset_t **) &new_pollset_ptr, new_size, poll_ptr->apr_pool_ptr, poll_flags ); if (status != 0) { jr_esprintf (error_buf, "couldn't create apr_pollset_t: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } jr_DListForEachElementPtr (poll_ptr->event_list, event_ptr) { status = jr_pollevent_add_to_pollset ( event_ptr, new_pollset_ptr, error_buf ); if (status != 0) { goto return_status; } } if (poll_ptr->apr_pollset_ptr) { apr_pollset_destroy (poll_ptr->apr_pollset_ptr); } poll_ptr->apr_pollset_ptr = new_pollset_ptr; poll_ptr->max_descriptors = new_size; new_pollset_ptr = 0; status = 0; return_status : { if (new_pollset_ptr) { apr_pollset_destroy (new_pollset_ptr); } } return status; } jr_pollevent_t *jr_poll_get_new_event ( jr_poll_t * poll_ptr, void * generic_io_ptr, jr_int poll_flags, jr_int (*opt_handler_fn) ( void * data_ptr, jr_poll_t * poll_ptr, void * generic_io_ptr, jr_int io_style_ready, char * error_buf ), void * opt_handler_data_ptr) { jr_pollevent_t * event_ptr; jr_int status; event_ptr = jr_DListNewTailPtr (poll_ptr->event_list); jr_pollevent_init (event_ptr, generic_io_ptr, poll_flags, opt_handler_fn, opt_handler_data_ptr); status = jr_HTableSetNewElementIndex (poll_ptr->event_table, &event_ptr); if (status < 0) { jr_pollevent_undo (event_ptr); jr_DListDeleteElement (poll_ptr->event_list, event_ptr); event_ptr = 0; } return event_ptr; } void jr_poll_delete_event ( jr_poll_t * poll_ptr, void * generic_io_ptr, jr_int poll_flags) { jr_pollevent_t event_info[1]; jr_pollevent_t * event_ptr = event_info; jr_pollevent_t ** event_ref; jr_int index; jr_pollevent_init (event_info, generic_io_ptr, poll_flags, 0, 0); index = jr_HTableFindElementIndex (poll_ptr->event_table, &event_ptr); if (index >= 0) { event_ref = jr_HTableElementPtr (poll_ptr->event_table, index); jr_HTableDeleteIndex (poll_ptr->event_table, index); jr_DListDeleteElement (poll_ptr->event_list, *event_ref); event_ptr = 0; } jr_pollevent_undo (event_info); } jr_int jr_poll_wait ( jr_poll_t * poll_ptr, jr_useconds_t * opt_interval_ptr, char * error_buf) { const apr_pollfd_t * apr_pollfd_array; apr_interval_time_t apr_interval; jr_pollevent_t * event_ptr; jr_int num_ready; jr_int q; jr_int status; if (poll_ptr->apr_pollset_ptr == 0) { jr_esprintf( error_buf, "no items to poll"); status = jr_MISUSE_ERROR; goto return_status; } if (opt_interval_ptr) { apr_interval = jr_useconds_to_64 (opt_interval_ptr); } else { apr_interval = -1; } status = apr_pollset_poll ( poll_ptr->apr_pollset_ptr, apr_interval, &num_ready, &apr_pollfd_array ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } jr_AListEmpty (poll_ptr->result_list); for (q=0; q < num_ready; q++) { event_ptr = apr_pollfd_array[q].client_data; event_ptr->io_style_ready = 0; if (apr_pollfd_array[q].rtnevents & APR_POLLIN) { event_ptr->io_style_ready |= jr_POLL_READ; } if (apr_pollfd_array[q].rtnevents & APR_POLLOUT) { event_ptr->io_style_ready |= jr_POLL_WRITE; } /* ** 3/28/09: May not need the HUP events, since under Linux ** a shutdown of one side generates a READ event on the other ** with 0 data. */ if (apr_pollfd_array[q].rtnevents & APR_POLLHUP) { event_ptr->io_style_ready |= jr_POLL_HUP; } /* ** 3-11-2011: APR_POLLRDHUP is added by the epoll-rdhup.patch. */ if (apr_pollfd_array[q].rtnevents & APR_POLLRDHUP) { event_ptr->io_style_ready |= jr_POLL_HUP; } jr_AListSetNewTail (poll_ptr->result_list, event_ptr); } status = jr_AListSize (poll_ptr->result_list); return_status : { } return status; } void jr_poll_wakeup ( jr_poll_t * poll_ptr) { if (poll_ptr->apr_pollset_ptr) { apr_pollset_wakeup ( poll_ptr->apr_pollset_ptr); } } void jr_pollevent_init ( jr_pollevent_t * event_ptr, void * generic_io_ptr, jr_int poll_flags, jr_int (*opt_handler_fn) ( void * data_ptr, jr_poll_t * poll_ptr, void * generic_io_ptr, jr_int io_style_ready, char * error_buf ), void * opt_handler_data_ptr) { memset (event_ptr, 0, sizeof (*event_ptr)); event_ptr->generic_io_ptr = generic_io_ptr; event_ptr->poll_flags = poll_flags; event_ptr->opt_handler_fn = opt_handler_fn; event_ptr->opt_handler_data_ptr = opt_handler_data_ptr; } void jr_pollevent_undo ( jr_pollevent_t * event_ptr) { } jr_int jr_pollevent_ptr_hash ( const void * void_ptr) { const jr_pollevent_t * event_ptr = *(jr_pollevent_t **)void_ptr; jr_int hash_value = 0; if (event_ptr->poll_flags && jr_POLL_IS_SOCKET) { hash_value += jr_socket_hash (event_ptr->generic_io_ptr); } if (event_ptr->poll_flags && jr_POLL_IS_FILE) { hash_value += jr_file_hash (event_ptr->generic_io_ptr); } return hash_value; } jr_int jr_pollevent_ptr_cmp ( const void * void_ptr_1, const void * void_ptr_2) { const jr_pollevent_t * event_ptr_1 = *(jr_pollevent_t **)void_ptr_1; const jr_pollevent_t * event_ptr_2 = *(jr_pollevent_t **)void_ptr_2; jr_int diff; diff = (event_ptr_1->poll_flags & jr_POLL_IS_MASK) - (event_ptr_2->poll_flags & jr_POLL_IS_MASK); if (diff != 0) { return diff; } if ((event_ptr_1->poll_flags & jr_POLL_IS_SOCKET) && (event_ptr_2->poll_flags & jr_POLL_IS_SOCKET)) { diff = jr_socket_cmp (event_ptr_1->generic_io_ptr, event_ptr_2->generic_io_ptr); if (diff != 0) { return diff; } } if ((event_ptr_1->poll_flags & jr_POLL_IS_FILE) && (event_ptr_2->poll_flags & jr_POLL_IS_FILE)) { diff = jr_file_cmp (event_ptr_1->generic_io_ptr, event_ptr_2->generic_io_ptr); if (diff != 0) { return diff; } } return 0; } jr_int jr_pollevent_add_to_pollset ( jr_pollevent_t * event_ptr, apr_pollset_t * apr_pollset_ptr, char * error_buf) { apr_pollfd_t apr_pollfd; jr_int status; memset (&apr_pollfd, 0, sizeof (apr_pollfd_t)); if (event_ptr->poll_flags & jr_POLL_IS_SOCKET) { apr_pollfd.desc_type = APR_POLL_SOCKET; apr_pollfd.desc.s = jr_socket_apr_ptr ((jr_socket_t *) event_ptr->generic_io_ptr); } if (event_ptr->poll_flags & jr_POLL_IS_FILE) { apr_pollfd.desc_type = APR_POLL_FILE; apr_pollfd.desc.f = jr_file_apr_ptr ((jr_file_t *) event_ptr->generic_io_ptr); } if (event_ptr->poll_flags & jr_POLL_READ) { apr_pollfd.reqevents |= APR_POLLIN; } if (event_ptr->poll_flags & jr_POLL_WRITE) { apr_pollfd.reqevents |= APR_POLLOUT; } if (event_ptr->poll_flags & jr_POLL_HUP) { apr_pollfd.reqevents |= APR_POLLHUP; if (event_ptr->poll_flags & jr_POLL_IS_SOCKET) { apr_pollfd.reqevents |= APR_POLLRDHUP; } } apr_pollfd.client_data = event_ptr; status = apr_pollset_add (apr_pollset_ptr, &apr_pollfd); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_poll_call_handler ( jr_poll_t * poll_ptr, jr_pollevent_t * event_ptr, char * error_buf) { jr_int status; if (event_ptr->opt_handler_fn) { status = (*event_ptr->opt_handler_fn) ( event_ptr->opt_handler_data_ptr, poll_ptr, event_ptr->generic_io_ptr, event_ptr->io_style_ready, error_buf ); } else { status = 0; } return status; }
frankjas/libjr
libjr/syscalls/jr_mutex_ms.c
<filename>libjr/syscalls/jr_mutex_ms.c #include "ezport.h" /* ** 3/9/07: in case ostype_winnt is defined in ezport.h */ #ifdef ostype_winnt #include <windows.h> #include <string.h> #include "jr/apr.h" typedef struct { HANDLE handle; CRITICAL_SECTION crit_section; } jr_mutex_ms_t; void jr_mutex_init ( jr_mutex_t * mutex_ptr, jr_int is_recursive) { jr_mutex_ms_t * ms_info_ptr = (void *) mutex_ptr->arch_data.microsoft_data; if (sizeof (jr_mutex_ms_t) > sizeof (mutex_ptr->arch_data.microsoft_data)) { abort(); } if (is_recursive) { InitializeCriticalSection (&(ms_info_ptr)->crit_section); } else { ms_info_ptr->handle = CreateEvent(NULL, FALSE, TRUE, NULL); } mutex_ptr->is_recursive = is_recursive != 0; } void jr_mutex_undo (mutex_ptr) jr_mutex_t * mutex_ptr; { jr_mutex_ms_t * ms_info_ptr = (void *) mutex_ptr->arch_data.microsoft_data; if (mutex_ptr->is_recursive) { DeleteCriticalSection (&(ms_info_ptr)->crit_section); } else { CloseHandle (ms_info_ptr->handle); } } void jr_mutex_lock (mutex_ptr) jr_mutex_t * mutex_ptr; { jr_mutex_ms_t * ms_info_ptr = (void *) mutex_ptr->arch_data.microsoft_data; if (mutex_ptr->is_recursive) { EnterCriticalSection (&(ms_info_ptr)->crit_section); } else { WaitForSingleObject(ms_info_ptr->handle, INFINITE); /* ** 3/2/07: can only return WAIT_OBJECT_0 (success) or WAIT_ABONDONED, which means ** the thread holding the mutex died before releasing it, ** which means the resource is free or the thread exitted unexpectedly, ** which means there's a bug in the program */ } } void jr_mutex_unlock (mutex_ptr) jr_mutex_t * mutex_ptr; { jr_mutex_ms_t * ms_info_ptr = (void *) mutex_ptr->arch_data.microsoft_data; if (mutex_ptr->is_recursive) { LeaveCriticalSection (&(ms_info_ptr)->crit_section); } else { if (SetEvent(ms_info_ptr->handle) == 0) { /* ** 3/2/07: error case. */ } } } /* ** 3/2/07: verify that the declaration macro is syntactically valid */ jr_thread_once_declare_and_init (TestControl); void jr_thread_once_call ( jr_thread_once_t * once_control_ptr, void (*some_func)()) { if (0) { TestControl.control_value = 0; /* 3/2/07: shutup compiler warning */ } if (!InterlockedExchange(&once_control_ptr->control_value, 1)) { (*some_func) (); } } #else #ifdef ostype_macosx #pragma GCC diagnostic ignored "-Winfinite-recursion" #endif static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/avl_tree/avl_path.c
#include "project.h" jr_int jr_AVL_TreeFillSearchPath (avl_tree, path, obj) jr_AVL_Tree * avl_tree; void ** path; const void * obj ; { void * curr_node; jr_int comp_val; jr_int path_index; /* * standard binary tree search. Much like * a binary search of an array */ curr_node = avl_tree->root_node; for (path_index = 0; curr_node; path_index ++) { path [path_index] = curr_node; comp_val = (*avl_tree->cmpfn)(obj, curr_node, avl_tree->cmpfn_arg) ; if (comp_val == 0) { return (path_index + 1) ; } if (comp_val < 0) curr_node = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node); else curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node); } return (path_index); } void *jr_AVL_TreeGetPrevPtrFromPath (avl_tree, path, path_length) jr_AVL_Tree * avl_tree; void ** path; jr_int path_length; { void * curr_node; jr_int path_index; path_index = path_length - 1; if (jr_AVL_TreeLeftChildPtr (avl_tree, path [path_index]) == 0) { /* * no left child, go up to parent * the bottom of the path could be left or right child. * If its the left child, then keep backing out until * you get an ancestor with a left child. * If its the right child, get the rightmost descendant * of the parent's left child, or the parent if there is no left child */ while (path_index > 0 && jr_AVL_TreeLeftChildPtr (avl_tree, path [path_index - 1]) == path [path_index]) { /* * while the current level is the left child of the parent */ path_index --; } if (path_index == 0) { /* * this node is the smallest node in the whole tree */ return (0); } /* * path index is a node that has a parent and is a right child */ return (path [path_index - 1]); } curr_node = jr_AVL_TreeLeftChildPtr (avl_tree, path [path_length - 1]); while (jr_AVL_TreeRightChildPtr (avl_tree, curr_node)) { curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node); } return (curr_node); } void *jr_AVL_TreePrevElementPtr (avl_tree, obj) jr_AVL_Tree * avl_tree; const void * obj ; { void * path [jr_AVL_TREE_MAX_HEIGHT]; jr_int path_length; void * prev_node; path_length = jr_AVL_TreeFillSearchPath (avl_tree, path, obj); if (path_length == 0) return (0); if ((*avl_tree->cmpfn) (obj, path [path_length - 1], avl_tree->cmpfn_arg) > 0) { /* * the object is greater than the bottom of the path, * so the bottom is the previous */ prev_node = path [path_length - 1]; } else { prev_node = jr_AVL_TreeGetPrevPtrFromPath (avl_tree, path, path_length); } return (prev_node); } void *jr_AVL_TreeGetNextPtrFromPath (avl_tree, path, path_length) jr_AVL_Tree * avl_tree; void ** path; jr_int path_length; { void * curr_node; jr_int path_index; path_index = path_length - 1; if (jr_AVL_TreeRightChildPtr (avl_tree, path [path_index]) == 0) { /* * no right child, go up to parent * the bottom of the path could be left or right child. * If its the right child, then keep backing out until * you get an ancestor with a right child. * If its the left child, get the leftmost descendant * of the parent's right child, or the parent if there is no right child */ while (path_index > 0 && jr_AVL_TreeRightChildPtr (avl_tree, path [path_index - 1]) == path [path_index]) { /* * while the current level is the right child of the parent */ path_index --; } if (path_index == 0) { /* * this node is the greatest node in the whole tree */ return (0); } /* * path index is a node that has a parent and is a left child */ return (path [path_index - 1]); } curr_node = jr_AVL_TreeRightChildPtr (avl_tree, path [path_length - 1]); while (jr_AVL_TreeLeftChildPtr (avl_tree, curr_node)) { curr_node = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node); } return (curr_node); } void *jr_AVL_TreeNextElementPtr (avl_tree, obj) jr_AVL_Tree * avl_tree; const void * obj ; { void * path [jr_AVL_TREE_MAX_HEIGHT]; jr_int path_length; void * next_node; path_length = jr_AVL_TreeFillSearchPath (avl_tree, path, obj); if (path_length == 0) return (0); if ((*avl_tree->cmpfn) (obj, path [path_length - 1], avl_tree->cmpfn_arg) < 0) { /* * the object is less than the bottom of the path, * so the bottom is the next */ next_node = path [path_length - 1]; } else { next_node = jr_AVL_TreeGetNextPtrFromPath (avl_tree, path, path_length); } return (next_node); }
frankjas/libjr
include/jr/exceptn.h
#ifndef _exception_h_ #define _exception_h_ #include "ezport.h" #include <setjmp.h> #include "jr/htable.h" /* * We don't want to require _POSIX_SOURCE to include this * file. So we use what we know is available in either case */ #ifdef _POSIX_SOURCE # define jr_sigsetjmp sigsetjmp # define jr_sigjmp_buf sigjmp_buf #else # define jr_sigsetjmp setjmp # define jr_sigjmp_buf jmp_buf #endif typedef struct { jr_sigjmp_buf jump_buffer; void (*handler_fn) (); char * error_buf; jr_int num_references; unsigned core_dump : 1; } jr_ExceptionType; extern jr_int jr_ExceptionRaiseWithCoreDump PROTO (( char * exception_name, jr_int core_dump, char * opt_error_buf )); extern jr_int jr_ExceptionBreakPoint PROTO (( jr_int status )); #define jr_ExceptionRaiseOrCoreDump(exception_name, opt_error_buf) \ jr_ExceptionRaiseWithCoreDump (exception_name, 1, opt_error_buf) #define jr_ExceptionRaise(exception_name, opt_error_buf) \ jr_ExceptionRaiseWithCoreDump (exception_name, 0, opt_error_buf) #define jr_ExceptionCatch(exception_name, error_buf) \ jr_sigsetjmp ( \ jr_ExceptionGetPtr (exception_name, error_buf)->jump_buffer, 1 \ ) #define jr_ExceptionCatchVector(exception_vector, error_buf) \ jr_sigsetjmp ( \ jr_ExceptionGetPtrFromVector (exception_vector, error_buf)->jump_buffer, 1 \ ) extern jr_ExceptionType * jr_ExceptionGetPtr PROTO (( char * exception_name, char * error_buf )); extern jr_ExceptionType * jr_ExceptionGetPtrFromVector PROTO (( char ** exception_vector, char * error_buf )); extern void jr_ExceptionUnCatchVector PROTO ((char **exception_vector)); extern void jr_ExceptionUnCatch PROTO ((char *exception_name)); extern void jr_ExceptionSetCoreDumpOnRaise PROTO (( char * exception_name, jr_int value )); #define jr_ExceptionCoreDumpOnRaise(exception_name) \ jr_ExceptionSetCoreDumpOnRaise (exception_name, 1) #define jr_ExceptionCatchOnRaise(exception_name) \ jr_ExceptionSetCoreDumpOnRaise (exception_name, 0) extern jr_HTable jr_ExceptionTable [1]; #define jr_ExceptionForEachName(index, exception_name) \ jr_HTableForEachElementIndex (jr_ExceptionTable, index) \ if (exception_name = jr_HTableKeyPtrValue (jr_ExceptionTable, index)) #endif
frankjas/libjr
include/jr/io.h
#ifndef __JR_IO_H__ #define __JR_IO_H__ #include "ezport.h" #include <stdio.h> #include <sys/types.h> #include "jr/error.h" #ifndef jr_MAXNAMLEN # define jr_MAXNAMLEN 244 #endif #ifndef jr_MAXPATHLEN # define jr_MAXPATHLEN 500 #endif #ifndef jr_MAXARGS # define jr_MAXARGS 500 #endif extern jr_int jr_Timed_fgets PROTO(( char * buffer, jr_int length, FILE * rfp, jr_int seconds )) ; extern jr_int jr_GetWholeLine PROTO (( char ** line_buf_ref, jr_int * line_buf_size_ref, FILE * rfp )); extern jr_int jr_FilePtrCopy PROTO (( FILE * wfp, FILE * rfp, char * error_buf )) ; extern int jr_FileNameCopy PROTO (( const char * dest_file_name, const char * src_file_name, char * error_buf )); extern jr_int jr_FirstLineOfFileName PROTO(( const char * rfn, char * result_buf, jr_int result_buf_length )) ; extern void jr_PrintArbitraryData PROTO (( FILE * wfp, const void * data_ptr, jr_int data_length, jr_int max_width )); extern void * jr_FileNameReadIntoNewMemory PROTO(( const char * rfn, unsigned jr_int * length_ptr )) ; extern void * jr_FilePtrReadIntoNewMemory PROTO(( FILE * rfp, unsigned jr_int * length_ptr )) ; /******** Path DB ********/ #define jr_PATH_DB_CONF_FILE "PathDB.cnf" #define jr_PATH_DB_CREATE_FLAG 0x0001 #define jr_PATH_DB_FILE_FLAG 0x0002 #define jr_PATH_DB_DIRECTORY_FLAG 0x0004 extern jr_int jr_PathDbMakePath ( const char * base_path, jr_int numeric_value, jr_int value_base, jr_int path_flags, const char ** balanced_path_ref, char * error_buf); /******** URL Library ********/ extern jr_int jr_URL_VerifyExistence PROTO (( char * machine_name, jr_int port_number, char * url_string, char * error_buf )); #define jr_HTTP_CONTINUE_STATUS 100 #define jr_HTTP_SUCCESS_STATUS 200 #define jr_HTTP_CREATED_STATUS 201 #define jr_HTTP_ACCEPTED_STATUS 202 #define jr_HTTP_NO_CONTENT_STATUS 204 #define jr_HTTP_MOVED_PERMANENTLY_STATUS 301 #define jr_HTTP_FOUND_STATUS 302 #define jr_HTTP_NOT_MODIFIED_STATUS 304 #define jr_HTTP_BAD_REQUEST_STATUS 400 #define jr_HTTP_UNAUTHORIZED_STATUS 401 #define jr_HTTP_FORBIDDEN_STATUS 403 #define jr_HTTP_NOT_FOUND_STATUS 404 #define jr_HTTP_URI_TOO_LONG_STATUS 414 #define jr_HTTP_SERVER_ERROR_STATUS 500 #define jr_HTTP_NOT_IMPLEMENTED_STATUS 501 #define jr_HTTP_BAD_GATEWAY_STATUS 502 #define jr_HTTP_SERVICE_UNAVAILABLE_STATUS 503 extern char * jr_HTTP_StatusString PROTO (( jr_int http_status )); #endif
frankjas/libjr
include/jr/memfile.h
<gh_stars>0 #ifndef _jr_memfile_h___ #define _jr_memfile_h___ #include "ezport.h" #include <stdio.h> #include "jr/alist.h" #define jr_MEM_FILE_TMP_BUF_LENGTH 32 typedef struct { jr_AList char_buffer [1]; jr_int max_buffer_size; jr_int rfd; jr_int wfd; FILE * fp; void * old_mask_ptr; jr_int num_string_opens; char tmp_file_name [jr_MEM_FILE_TMP_BUF_LENGTH]; unsigned saw_eof : 1; unsigned created_tmp_file : 1; } jr_MemoryFileType; extern jr_MemoryFileType *jr_MemoryFileCreateForWriting PROTO (( jr_int max_buffer_size, char * error_buf )); extern void jr_MemoryFileDestroy PROTO (( jr_MemoryFileType * mem_file_ptr )); extern const char * jr_MemoryFileOpenString PROTO (( jr_MemoryFileType * mem_file_ptr )); extern void jr_MemoryFileCloseString PROTO (( jr_MemoryFileType * mem_file_ptr, const char * string )); #define jr_MemoryFilePtr(mem_file_ptr) ((mem_file_ptr)->fp) #endif
frankjas/libjr
libjr/dlist/project.h
#ifndef __project_h___ #define __project_h___ #define _POSIX_SOURCE 1 #include "ezport.h" #include <assert.h> #include <stdarg.h> #include "jr/dlist.h" #include "jr/malloc.h" #include "jr/alist.h" #include "jr/prefix.h" #endif
frankjas/libjr
libjr/missing/sigsuspend.c
<gh_stars>0 #define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_sigaction_objects #include <sys/types.h> #include <unistd.h> #include <signal.h> int sigsuspend(set) const sigset_t * set ; { int mask = *set ; return sigpause(mask) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/syscalls/pathsrch.c
<reponame>frankjas/libjr #define _POSIX_SOURCE 1 #include "ezport.h" #include <unistd.h> #include <string.h> #include "jr/syscalls.h" #include "jr/malloc.h" char *jr_PathSearch (file_name, dir_vector) char * file_name; char ** dir_vector; { char * file_path; char * curr_dir; jr_int i; jr_int status; for (i=0; dir_vector[i]; i++) { curr_dir = dir_vector[i]; file_path = jr_malloc (strlen (curr_dir) + 1 + strlen (file_name) + 1); sprintf (file_path, "%s/%s", curr_dir, file_name); status = access (file_path, R_OK); jr_free (file_path); if (status == 0) { return curr_dir; } } return 0; }
frankjas/libjr
libjr/syscalls/jr_file.c
<gh_stars>0 #include "ezport.h" #include <string.h> #include <apr-1/apr_pools.h> #include <apr-1/apr_file_io.h> #include <apr-1/apr_errno.h> #include <apr-1/apr_portable.h> #ifdef ostype_winnt # include <io.h> #endif #include "jr/apr.h" #include "jr/error.h" #include "jr/misc.h" #include "jr/syscalls.h" #include "jr_apr.h" void jr_file_init ( jr_file_t * file_info) { memset (file_info, 0, sizeof (jr_file_t)); jr_apr_initialize(); } void jr_file_undo ( jr_file_t * file_info) { if (file_info->apr_pool_ptr) { /* ** 5/13/08: If there's no pool, there's either no apr_file_ptr or it's the write ** of a pipe, which will be closed when the parent pipe is closed. */ if (file_info->apr_file_ptr) { apr_file_close (file_info->apr_file_ptr); } apr_pool_destroy (file_info->apr_pool_ptr); } if (file_info->aprbuf_ptr) { jr_aprbuf_destroy (file_info->aprbuf_ptr); } } jr_int jr_file_cmp ( const void * void_ptr_1, const void * void_ptr_2) { const jr_file_t * file_ptr_1 = void_ptr_1; const jr_file_t * file_ptr_2 = void_ptr_2; return jr_ptrcmp (file_ptr_1->apr_file_ptr, file_ptr_2->apr_file_ptr); } jr_int jr_file_hash ( const void * void_ptr) { const jr_file_t * file_ptr = void_ptr; return jr_ptrhash (file_ptr->apr_file_ptr); } jr_int jr_file_open ( jr_file_t * file_info, const char * file_name, jr_int open_flags, jr_int file_perms, char * error_buf) { apr_int32_t apr_flags = 0; apr_fileperms_t apr_perms = 0; jr_int status; if (file_info->apr_pool_ptr == 0) { status = apr_pool_create ((apr_pool_t **) &file_info->apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } else { if (file_info->apr_file_ptr) { apr_file_close (file_info->apr_file_ptr); } } if (open_flags & jr_FILE_OPEN_READ) { apr_flags |= APR_FOPEN_READ; } if (open_flags & jr_FILE_OPEN_WRITE) { apr_flags |= APR_FOPEN_WRITE; } if (open_flags & jr_FILE_OPEN_APPEND) { apr_flags |= APR_FOPEN_APPEND; } if (open_flags & jr_FILE_OPEN_CREATE) { apr_flags |= APR_FOPEN_CREATE; } if (open_flags & jr_FILE_OPEN_TRUNCATE) { apr_flags |= APR_FOPEN_TRUNCATE; } if (open_flags & jr_FILE_OPEN_BUFFERED) { apr_flags |= APR_FOPEN_BUFFERED; } if (open_flags & jr_FILE_OPEN_DEL_ON_CLOSE) { apr_flags |= APR_FOPEN_DELONCLOSE; } if (open_flags & jr_FILE_OPEN_EXCLUSIVE) { apr_flags |= APR_FOPEN_EXCL; } apr_perms = jr_PermsToUmaskedAprPerms( file_perms & ~(jr_PERM_X_OWNER | jr_PERM_X_GROUP | jr_PERM_X_OTHER) ); /* ** 2-25-2012: to mimic Unix behavior, always mask the execute bit ** when creating files. */ status = apr_file_open ( (apr_file_t **) &file_info->apr_file_ptr, file_name, apr_flags, apr_perms, file_info->apr_pool_ptr ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_file_close ( jr_file_t * file_info, char * error_buf) { jr_int status; if (file_info->aprbuf_ptr && jr_aprbuf_needs_flush (file_info->aprbuf_ptr)) { status = jr_file_flush (file_info, error_buf); if (status != 0) { goto return_status; } } if (file_info->apr_file_ptr) { status = apr_file_close (file_info->apr_file_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } } status = 0; return_status : { /* ** 2/13/07: this should behave as though the close actually worked */ if (file_info->apr_pool_ptr) { apr_pool_destroy (file_info->apr_pool_ptr); } file_info->apr_file_ptr = 0; file_info->apr_pool_ptr = 0; } return status; } jr_int jr_file_open_stdin ( jr_file_t * file_info, char * error_buf) { jr_int status; if (file_info->apr_pool_ptr == 0) { status = apr_pool_create ((apr_pool_t **) &file_info->apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } status = apr_file_open_stdin ( (apr_file_t **) &file_info->apr_file_ptr, file_info->apr_pool_ptr ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_file_open_stdout ( jr_file_t * file_info, char * error_buf) { jr_int status; if (file_info->apr_pool_ptr == 0) { status = apr_pool_create ((apr_pool_t **) &file_info->apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } status = apr_file_open_stdout ( (apr_file_t **) &file_info->apr_file_ptr, file_info->apr_pool_ptr ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_file_open_stderr ( jr_file_t * file_info, char * error_buf) { jr_int status; if (file_info->apr_pool_ptr == 0) { status = apr_pool_create ((apr_pool_t **) &file_info->apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } status = apr_file_open_stderr ( (apr_file_t **) &file_info->apr_file_ptr, file_info->apr_pool_ptr ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_file_open_pipe ( jr_file_t * read_file_info, jr_file_t * write_file_info, char * error_buf) { jr_int status; if (read_file_info->apr_pool_ptr == 0) { status = apr_pool_create ((apr_pool_t **) &read_file_info->apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } /* ** 5/9/08: Note that the APR documentation is misleading. The actual ** test code reads from the first pipe argument. */ status = apr_file_pipe_create ( (apr_file_t **) &read_file_info->apr_file_ptr, (apr_file_t **) &write_file_info->apr_file_ptr, read_file_info->apr_pool_ptr ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_file_open_tmp ( jr_file_t * file_info, char * file_name, jr_int open_flags, jr_int file_perms, char * error_buf) { jr_int status; open_flags |= jr_FILE_OPEN_WRITING | jr_FILE_OPEN_EXCLUSIVE; jr_MkTemp( file_name ); status = jr_file_open( file_info, file_name, open_flags, file_perms, error_buf ); return status; } int jr_file_setbufsize( jr_file_t * file_info, jr_int buf_size, char * error_buf) { char * buffer; jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } buffer = apr_palloc( file_info->apr_pool_ptr, buf_size ); status = apr_file_buffer_set( file_info->apr_file_ptr, buffer, buf_size ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } FILE *jr_file_stdio_open_dont_use( jr_file_t * file_info, const char * how, char * error_buf) { FILE * fp; apr_os_file_t handle; jr_int status; /* ** 3/26/09: NOTE: the problem with this API is that you can't close the FILE* ** without closing the underlying jr_file_t, rendering the jr_file_t useless. */ status = apr_os_file_get( &handle, file_info->apr_file_ptr ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); fp = NULL; goto return_fp; } # ifdef ostype_winnt { /* ** 3/26/09: the apr_os_file_t is equivalent to a HANDLE */ jr_int crt_handle; crt_handle = _open_osfhandle ((intptr_t) handle, _O_RDWR); if (crt_handle < 0) { CloseHandle (handle); jr_esprintf (error_buf, "couldn't _open_osfhandle(): %s", strerror (errno)); fp = NULL; goto return_fp; } fp = _fdopen( crt_handle, how ); if (fp == NULL) { _close (crt_handle); /* 2/8/07: closes 'handle' implicitly */ jr_esprintf (error_buf, "couldn't fdopen(): %s", strerror (errno)); goto return_fp; } } # else { fp = fdopen (handle, how ); if (fp == NULL) { jr_esprintf (error_buf, "couldn't fdopen(): %s", strerror (errno)); goto return_fp; } } # endif return_fp : { } return fp; } jr_int jr_file_read ( jr_file_t * file_info, void * data_buf, unsigned jr_int data_buf_len, char * error_buf) { apr_size_t apr_length = data_buf_len; jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } if (data_buf_len > jr_INT_MAX) { jr_esprintf (error_buf, "read length %d too large, max is %d", data_buf_len, jr_INT_MAX); status = jr_MISUSE_ERROR; goto return_status; } status = apr_file_read (file_info->apr_file_ptr, data_buf, &apr_length); if (status == APR_EOF) { /* ** 3-12-2013: changing this to jr_EOF_ERROR will ripple through fcache, OTF, OTN, ** OTC, OTA, libcw, where the 0 return value on EOF is used to stop a loop. ** In libcw, look for ar_BytesObjectReadData(). */ apr_length = 0; } else if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); /* ** 2/13/07: apr_file_read() returns apr_get_os_error() */ # ifdef ostype_winnt { status = jr_ConvertLastError (APR_TO_OS_ERROR(status)); } # else { status = jr_ConvertErrno (APR_TO_OS_ERROR(status)); } # endif goto return_status; } status = (jr_int) apr_length; return_status : { } return status; } jr_int jr_file_write ( jr_file_t * file_info, const void * data_buf, unsigned jr_int data_buf_len, char * error_buf) { apr_size_t apr_length = data_buf_len; jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } if (data_buf_len > jr_INT_MAX) { jr_esprintf (error_buf, "write length %d too large, max is %d", data_buf_len, jr_INT_MAX); status = jr_MISUSE_ERROR; goto return_status; } if (file_info->aprbuf_ptr && jr_aprbuf_needs_flush (file_info->aprbuf_ptr)) { /* ** 3/29/08: allow abitrary combinations of jr_file_write() and jr_file_printf() */ status = jr_file_flush (file_info, error_buf); if (status != 0) { goto return_status; } } status = apr_file_write (file_info->apr_file_ptr, data_buf, &apr_length); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = (jr_int) apr_length; return_status : { } return status; } jr_int jr_file_printf ( jr_file_t * file_info, const char * control_string, ...) { va_list arg_list; jr_int nbytes; jr_int status; if (file_info->apr_file_ptr == 0) { status = jr_MISUSE_ERROR; goto return_status; } va_start (arg_list, control_string); if (file_info->aprbuf_ptr == 0) { file_info->aprbuf_ptr = jr_aprbuf_create( file_info, (jr_aprbuf_writefn_t) jr_file_write, 8 * 1024 ); } jr_aprbuf_set_error_buf (file_info->aprbuf_ptr, 0); status = jr_aprbuf_vformatter ( file_info->aprbuf_ptr, control_string, arg_list ); if (status < 0) { /* ** 2/7/07: only fails if flush() fails, so use that status, error_buf already filled in */ status = jr_ConvertAprErrno (jr_aprbuf_status (file_info->aprbuf_ptr)); goto return_status; } else { nbytes = status; } /* ** 3/29/08: Not all data may be written out, need to call jr_file_flush() ** to flush any buffered data. */ status = nbytes; return_status : { va_end (arg_list); } return status; } jr_int jr_file_flush ( jr_file_t * file_info, char * error_buf) { jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } if (file_info->aprbuf_ptr && jr_aprbuf_needs_flush (file_info->aprbuf_ptr)) { jr_aprbuf_set_error_buf (file_info->aprbuf_ptr, error_buf); status = jr_aprbuf_flush (file_info->aprbuf_ptr); if (status != 0) { goto return_status; } } status = apr_file_flush (file_info->apr_file_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_file_sync ( jr_file_t * file_info, char * error_buf) { jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } status = apr_file_sync (file_info->apr_file_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_file_seek ( jr_file_t * file_info, jr_ULong offset, jr_int whence, char * error_buf) { apr_off_t apr_offset = jr_ULongToHost64 (offset); jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } if (whence == jr_FILE_SEEK_CUR) { whence = APR_CUR; } else if (whence == jr_FILE_SEEK_END) { whence = APR_END; } else { whence = APR_SET; } status = apr_file_seek (file_info->apr_file_ptr, whence, &apr_offset); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } /* ** 1/29/07: apr_offset contains the new offset */ status = 0; return_status : { } return status; } jr_int jr_file_truncate ( jr_file_t * file_info, jr_ULong offset, char * error_buf) { apr_off_t apr_offset = jr_ULongToHost64 (offset); apr_int32_t apr_flags; jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } apr_flags = apr_file_flags_get( file_info->apr_file_ptr); if (apr_flags & APR_FOPEN_BUFFERED) { status = jr_file_flush( file_info, error_buf); if (status != 0) { jr_esprintf( error_buf, "couldn't flush before truncate: %s", error_buf); goto return_status; } } status = apr_file_trunc (file_info->apr_file_ptr, apr_offset); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_file_get_offset ( jr_file_t * file_info, jr_ULong * offset_ref, char * error_buf) { apr_off_t apr_offset = 0; jr_int whence; jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } whence = APR_CUR; status = apr_file_seek (file_info->apr_file_ptr, whence, &apr_offset); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } /* ** 1/29/07: apr_offset contains the new offset */ jr_ULongAsgn64 (offset_ref, apr_offset); status = 0; return_status : { } return status; } jr_int jr_file_gets ( jr_file_t * file_info, char * buffer, jr_int buffer_length, char * error_buf) { jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } status = apr_file_gets (buffer, buffer_length, file_info->apr_file_ptr); if (status == APR_EOF) { jr_esprintf (error_buf, "end of input"); status = jr_EOF_ERROR; goto return_status; } else if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); /* ** 2/13/07: apr_file_read() returns apr_get_os_error() */ # ifdef ostype_winnt { status = jr_ConvertLastError (APR_TO_OS_ERROR(status)); } # else { status = jr_ConvertErrno (APR_TO_OS_ERROR(status)); } # endif goto return_status; } status = 0; return_status : { } return status; } jr_int jr_file_is_tape( jr_file_t * file_info, char * error_buf) { jr_stat_t stat_info[1]; jr_int status; status = jr_file_stat (file_info, stat_info, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't 'stat' file pointer: %s", error_buf); return -1; } return jr_stat_is_char_dev( stat_info ); } jr_int jr_file_stat_common ( jr_file_t * file_info, jr_int flags, jr_stat_t * opt_jr_stat_ptr, const char ** opt_user_name_ref, const char ** opt_group_name_ref, char * error_buf) { apr_finfo_t apr_finfo[1]; apr_pool_t * apr_pool_ptr = 0; jr_int info_bits = APR_FINFO_NORM; jr_int status; if (file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "file not open"); status = jr_MISUSE_ERROR; goto return_status; } jr_apr_initialize(); apr_pool_create (&apr_pool_ptr, NULL); status = apr_file_info_get (apr_finfo, info_bits, file_info->apr_file_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = jr_stat_prepare_return( opt_jr_stat_ptr, flags, opt_user_name_ref, opt_group_name_ref, apr_finfo, apr_pool_ptr, error_buf ); if (status != 0) { goto return_status; } status = 0; return_status : { apr_pool_destroy (apr_pool_ptr); } return status; } jr_int jr_file_copy( jr_file_t * dest_file_info, jr_file_t * src_file_info, char * error_buf) { apr_pool_t * apr_pool_ptr = 0; apr_file_t * apr_dest_ptr; apr_file_t * apr_src_ptr; apr_size_t dest_buf_size; apr_size_t src_buf_size; apr_off_t src_pos; char * data_buf; apr_size_t data_buf_len; apr_size_t apr_length; apr_size_t bytes_written; apr_size_t bytes_read; jr_int status; /* ** 3/28/09: Dup the original files so we can turn off buffering. */ if (src_file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "source file not open"); status = jr_MISUSE_ERROR; goto return_status; } if (dest_file_info->apr_file_ptr == 0) { jr_esprintf (error_buf, "destination file not open"); status = jr_MISUSE_ERROR; goto return_status; } status = apr_pool_create( &apr_pool_ptr, NULL ); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } dest_buf_size = apr_file_buffer_size_get( dest_file_info->apr_file_ptr ); src_buf_size = apr_file_buffer_size_get( src_file_info->apr_file_ptr ); if (dest_buf_size > src_buf_size) { data_buf_len = dest_buf_size; } else { data_buf_len = src_buf_size; } if (data_buf_len <= 0) { data_buf_len = 8192; } data_buf = apr_palloc( apr_pool_ptr, data_buf_len ); if (data_buf == 0) { jr_esprintf (error_buf, "couldn't allocate data buf"); status = jr_ConvertAprErrno (status); goto return_status; } src_pos = 0; status = apr_file_seek( src_file_info->apr_file_ptr, APR_CUR, &src_pos ); if (status != 0) { jr_esprintf( error_buf, "couldn't get src. initial position: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } status = apr_file_dup( &apr_dest_ptr, dest_file_info->apr_file_ptr, apr_pool_ptr ); if (status != 0) { jr_esprintf( error_buf, "couldn't dup. dest. file: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } status = apr_file_dup( &apr_src_ptr, src_file_info->apr_file_ptr, apr_pool_ptr ); if (status != 0) { jr_esprintf( error_buf, "couldn't dup. dest. file: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } /* ** 3/28/09: turn off buffering */ status = apr_file_buffer_set( apr_dest_ptr, 0, 0 ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = apr_file_buffer_set( apr_src_ptr, 0, 0 ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } while (1) { apr_length = data_buf_len; status = apr_file_read (apr_src_ptr, data_buf, &apr_length); if (status == APR_EOF) { break; } else if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); /* ** 2/13/07: apr_file_read() returns apr_get_os_error() */ # ifdef ostype_winnt { status = jr_ConvertLastError (APR_TO_OS_ERROR(status)); } # else { status = jr_ConvertErrno (APR_TO_OS_ERROR(status)); } # endif goto return_status; } bytes_written = 0; bytes_read = apr_length; while (bytes_written < bytes_read) { apr_length = bytes_read - bytes_written; status = apr_file_write (apr_dest_ptr, data_buf + bytes_written, &apr_length); if (apr_length > 0) { bytes_written += apr_length; } else if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } } } /* ** 3/29/09: the following seek() is to overcome a "bug" in APR, where non-dup()ed ** src file's offset is not maintained properly. The apr_file_t apparently ** caches the file offset (in filePtr). The dup()ed src changes the actual ** system file offset but calls to apr_file_seek() on the original have no effect ** because APR doesn't take this into account. */ status = apr_file_seek( apr_src_ptr, APR_SET, &src_pos ); if (status != 0) { jr_esprintf( error_buf, "couldn't reset src. position: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { apr_pool_destroy (apr_pool_ptr); } return status; }
frankjas/libjr
libjr/missing/flock.c
<gh_stars>0 #define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_flock_objects #include <errno.h> #include <fcntl.h> #include <unistd.h> int flock (fd, operation) int fd; int operation; { struct flock new_lock [1]; jr_int status; new_lock->l_whence = SEEK_SET; new_lock->l_start = 0; new_lock->l_len = 0; if (operation & LOCK_UN) { new_lock->l_type = F_UNLCK; } if (operation & LOCK_SH) { new_lock->l_type = F_RDLCK; } if (operation & LOCK_EX) { new_lock->l_type = F_WRLCK; } if (operation & LOCK_NB) { status = fcntl (fd, F_SETLK, new_lock); } else { status = fcntl (fd, F_SETLKW, new_lock); } return status; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/string/scanf.c
#include "ezport.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include <string.h> #define JR_SCANF_USE_ARG_FOR_VALUE -1 #define JR_SCANF_NO_WIDTH_SPECIFIED -2 #define JR_SCANF_VARARG_PROTECT 1 #include "jr/string.h" /* * In this module the scanf specifier %n will not be supported */ typedef struct { /* "%15.12s" means absorb 15 input columns, restrict output string to 11 chars plus null */ /* "%.12[A-Z] means absorb all the upper case letters and store up to 11 of them plus null */ /* "%15.12[A-Z] means absorb 15 input columns storing up to 11 upper case letters plus null */ /* "%15.12f" means absorb 15 input columns, only first 12 used for float value interpretation */ /* SET IN INITIALIZATION */ jr_int number_of_input_columns ; /* the 15 in examples above */ jr_int output_array_bounds ; /* the 12 in examples above */ jr_int was_leading_zero ; /* %#010x the 0 after the pound sign */ jr_int was_pound ; /* the pound sign in example above */ jr_int was_left_justified ; /* %-15.12s minus sign indicates left justified */ const char * start_of_sequence ; /* a pointer to the place right after the % */ const char * middle_of_sequence ; /* points to the 'ld' in %010ld */ const char * end_of_sequence ; /* a pointer to the trailing 's' 'f' or 'x' */ /* SET DURING EXECUTION */ const char * new_input_char_ptr ; /* gives position after input has been interpreted */ va_list new_arg_list ; /* after the args have been used/filled */ } jr_ScanfControlStruct ; extern void jr_ColumnScanfInitControlStruct( jr_ScanfControlStruct * control_sp, const char * control_char_ptr ) ; extern jr_int jr_ColumnScanfExecuteControlSequence( jr_ScanfControlStruct * control, /* use this struct to match and control assignment */ const char * input_char_ptr /* use this string to match against and assign from */ ) ; extern jr_int jr_ScanfSetContainsCharacter( const char * scanf_char_set, jr_int char_value ) ; jr_int jr_ColumnScanf( const char * input_str, const char * control_str, ...) { va_list arg_list; jr_ScanfControlStruct control_sp[1] ; jr_int number_of_percent_items_interpreted = 0 ; const char * input_char_ptr ; const char * control_char_ptr ; va_start (arg_list, control_str); input_char_ptr = input_str ; for (control_char_ptr = control_str ; *control_char_ptr ; control_char_ptr++) { # ifdef JR_SCANF_TRACE fprintf(stderr, "START with: %s\n", input_char_ptr) ; # endif switch (*control_char_ptr) { case '%' : { control_char_ptr++ ; /* skip over percent that starts control sequence */ if (*control_char_ptr != '%') { jr_int status ; jr_ColumnScanfInitControlStruct(control_sp, control_char_ptr) ; va_copy (control_sp->new_arg_list, arg_list); control_char_ptr = control_sp->end_of_sequence ; status = jr_ColumnScanfExecuteControlSequence( control_sp, /* use this struct to match and control assignment */ input_char_ptr /* use this string to match against and assign from */ ) ; if (status != 0) { goto return_point ; } # ifdef JR_SCANF_TRACE fprintf(stderr, "current stack ptr == %#010x\n", &arg_list) ; fprintf(stderr, "new stack ptr == %#010x\n", &control_sp->new_arg_list) ; # endif va_copy (arg_list, control_sp->new_arg_list); input_char_ptr = control_sp->new_input_char_ptr ; number_of_percent_items_interpreted++ ; break ; } else { /* then fall through because a second percent is like any other char */ } } default : { switch(*control_char_ptr) { case ' ' : { while (isspace(*input_char_ptr)) { # ifdef JR_SCANF_TRACE fprintf(stderr,"skipping blank on input\n") ; # endif input_char_ptr++ ; } break ; } default : { if (*control_char_ptr == *input_char_ptr) { # ifdef JR_SCANF_TRACE fprintf(stderr,"fixed input matched '%c'\n", *input_char_ptr) ; # endif input_char_ptr++ ; } else { # ifdef JR_SCANF_TRACE fprintf(stderr,"control string '%c' != '%c' so stopping\n", *control_char_ptr, *input_char_ptr ) ; # endif /* input failed to match control string, we are done! */ goto return_point ; } break ; } } break ; /* out of switch on control_char */ } } } /* while there are more control characters */ return_point: va_end (arg_list); return(number_of_percent_items_interpreted) ; } void jr_ColumnScanfInitControlStruct(control_sp, control_char_ptr) jr_ScanfControlStruct * control_sp ; const char * control_char_ptr ; { memset((void *)control_sp, 0, sizeof(*control_sp)) ; control_sp->output_array_bounds = JR_SCANF_NO_WIDTH_SPECIFIED ; control_sp->number_of_input_columns = JR_SCANF_NO_WIDTH_SPECIFIED ; control_sp->start_of_sequence = control_char_ptr ; for ( ; *control_char_ptr ; control_char_ptr++) { if (*control_char_ptr == '#') { control_sp->was_pound++ ; continue ; } else if (*control_char_ptr == '-') { control_sp->was_left_justified++ ; continue ; } else if (*control_char_ptr == '0') { control_sp->was_leading_zero++ ; continue ; } else if (isdigit(*control_char_ptr)) { if (control_sp->number_of_input_columns < 0) control_sp->number_of_input_columns = 0 ; control_sp->number_of_input_columns = (control_sp->number_of_input_columns * 10) + (*control_char_ptr - '0') ; } else if (*control_char_ptr == '*') { control_sp->number_of_input_columns = JR_SCANF_USE_ARG_FOR_VALUE ; /* break ; commented out FJ 4/14/94 */ /* so that end_of_sequence won't be 0 if we see %*s */ } else if (*control_char_ptr == '.') { break ; } else { control_sp->end_of_sequence = control_char_ptr ; goto return_point ; } } if (*control_char_ptr == 0) { control_sp->end_of_sequence = control_char_ptr ; goto return_point ; } if (*control_char_ptr == '.') { control_char_ptr++ ; /* skip over dot, look for array bounds spec */ for ( ; *control_char_ptr ; control_char_ptr++) { if (*control_char_ptr == '#') { continue ; } else if (isdigit(*control_char_ptr)) { if (control_sp->output_array_bounds < 0) control_sp->output_array_bounds = 0 ; control_sp->output_array_bounds = (control_sp->output_array_bounds * 10) + (*control_char_ptr - '0') ; } else if (*control_char_ptr == '*') { control_sp->output_array_bounds = JR_SCANF_USE_ARG_FOR_VALUE ; /* break ; commented out 2/27/94 */ } else { control_sp->end_of_sequence = control_char_ptr ; goto return_point ; } } } return_point: control_sp->middle_of_sequence = control_sp->end_of_sequence ; if ( ( (*control_sp->end_of_sequence == 'l') || (*control_sp->end_of_sequence == 'h') ) && (strchr("doxefg", control_sp->end_of_sequence[1]) != 0) ) { control_sp->end_of_sequence++ ; } else if (*control_sp->end_of_sequence == '[') { while (*control_sp->end_of_sequence) { if (*control_sp->end_of_sequence == ']') break ; control_sp->end_of_sequence++ ; } } return ; } jr_int jr_ColumnScanfExecuteControlSequence(control_sp, input_char_ptr) jr_ScanfControlStruct * control_sp ; /* use this struct to match and control assignment */ const char * input_char_ptr ; /* use this string to match against and assign from */ { char my_control_sequence[512] ; char * my_input_string ; jr_int status = 0 ; jr_int i ; /* extract the %f or %ld from %#15.12d */ { strcpy(my_control_sequence, "%") ; strncat( my_control_sequence, control_sp->middle_of_sequence, control_sp->end_of_sequence - control_sp->middle_of_sequence + 1 ) ; /* * 4/14/93 FJ: added strncat to only copy the current format specifier * this copies all the following format specifiers, some of * which will be 'ColumnScanf' style, which will screw up the sscanf * below, which gets called if the thing is a %d, %f, etc. * Note: my_control_sequence is only used with the sscanf, put this code below? */ } /* fill in run time assigned width values as in %*.*s */ { if (control_sp->number_of_input_columns == JR_SCANF_USE_ARG_FOR_VALUE) { jr_int width_spec = va_arg(control_sp->new_arg_list, jr_int) ; control_sp->number_of_input_columns = width_spec ; } if (control_sp->output_array_bounds == JR_SCANF_USE_ARG_FOR_VALUE) { jr_int width_spec = va_arg(control_sp->new_arg_list, jr_int) ; control_sp->output_array_bounds = width_spec ; } } /* * it is guaranteed that our copy of the input characters won't need to be longer * than the original */ my_input_string = (char *) alloca(strlen(input_char_ptr) + 1) ; /* make our own null ended copy of the input string and increment the input_char_ptr */ { /* * There are two ways the number of input columns for each argument * can be specified: by number as in %15s OR by 'scanf set' %.15[A-Z] */ jr_int saw_end_of_matching_chars = 0 ; jr_int i ; for (i = 0 ; input_char_ptr[i] ; i++) { if (input_char_ptr[i] == 0) break ; if ((*control_sp->middle_of_sequence == '[') && (! jr_ScanfSetContainsCharacter(control_sp->middle_of_sequence, input_char_ptr[i]))) { saw_end_of_matching_chars++ ; if (control_sp->number_of_input_columns < 0) { /* * no specific number of columns was specified * and the input characters no longer match our set so break */ break ; } } if ((control_sp->number_of_input_columns >= 0) && (i >= control_sp->number_of_input_columns)) { /* a specific number of input columns was specified and we are there so break */ break ; } /* * added FJ 4/14/94 (modified by will to NOT break if there were %[] chars) */ if ((*control_sp->middle_of_sequence != '[') && (control_sp->number_of_input_columns == JR_SCANF_NO_WIDTH_SPECIFIED) && isspace(input_char_ptr[i]) ) { /* * no input column length was specified, and we saw a blank, so the string is done */ break; } if (saw_end_of_matching_chars) { my_input_string[i] = 0 ; } else { my_input_string[i] = input_char_ptr[i] ; } } my_input_string[i] = 0 ; control_sp->new_input_char_ptr = input_char_ptr + i ; } /* end of block for our own null ended copy of input chars and incrementing input_char_ptr */ /* * At this point we have a copy of the input in my_input_string * which is at most number_of_input_columns long and contains * only those characters which were in the specified set (if there was a set). */ if ((*control_sp->end_of_sequence == 's') || (*control_sp->middle_of_sequence == '[')) { char * output_buffer = va_arg(control_sp->new_arg_list, char *) ; char * input_ptr ; /* * Now we will copy just the portion of my_input_string * which will fit into the output_buffer */ if (*my_input_string == 0 && (*control_sp->middle_of_sequence != '[' && control_sp->number_of_input_columns != 0)) { /* * added 4/28/95, if there is not enough input, we * should return a bad status, except if a set was requested or * 0 columns were requested (%[] implies 0 or more characters matching). */ status = -1; } else if (control_sp->output_array_bounds >= 0) { input_ptr = my_input_string ; for (i=0; i < (control_sp->output_array_bounds - 1); i++) { output_buffer[i] = *input_ptr ; if (*input_ptr) input_ptr++ ; } output_buffer[i] = 0 ; } else { strcpy(output_buffer, my_input_string) ; } } else { /* * Now we will the real scanf handle all the numeric conversions */ jr_int item_was_scanned ; my_input_string[control_sp->output_array_bounds] = 0 ; item_was_scanned = sscanf( my_input_string, my_control_sequence, va_arg(control_sp->new_arg_list, void *) ) ; if (item_was_scanned != 1) { /* * FJ 4/14/94: sscanf may return -1 (EOF) if input error * occurs before any conversion (i.e. a null string) */ status = -1 ; } } return(status) ; } jr_int jr_ScanfSetContainsCharacter(scanf_char_set_arg, char_value) const char * scanf_char_set_arg ; jr_int char_value ; { const char * scanf_char_set = scanf_char_set_arg ; jr_int reverse_sense_of_comparison = 0 ; jr_int matched = 0; jr_int left_side_of_dash = 077777; jr_int scanf_set_character ; jr_int return_value ; if (*scanf_char_set == '[') { scanf_char_set++ ; /* skip over opening '[' */ if (*scanf_char_set == '^') { scanf_char_set++ ; /* skip over and remember NOT character '^' */ reverse_sense_of_comparison++ ; } } while (scanf_set_character = *scanf_char_set++) { if (scanf_set_character == ']') { break ; } if (scanf_set_character == '-') { if ((left_side_of_dash <= char_value) && (char_value <= *scanf_char_set++)) { matched++; } } else { if (char_value == (left_side_of_dash = scanf_set_character)) { matched++; } } } return_value = (reverse_sense_of_comparison) ? (! matched) : matched ; # ifdef JR_SCANF_TRACE fprintf(stderr,"%s: %c is %s part of set\n", scanf_char_set_arg, char_value, return_value ? "" : "NOT" ) ; # endif return(return_value) ; }
frankjas/libjr
libjr/misc/esis_prj.h
#ifndef __esis_proj_h___ #define __esis_proj_h___ #define _POSIX_SOURCE 1 #include "ezport.h" #include <ctype.h> #include <errno.h> #include <stdlib.h> #include "jr/string.h" #include "jr/malloc.h" #include "jr/error.h" #include "jr/prefix.h" #include "jr/misc.h" #include "jr/esis/lib.h" extern void jr_ESIS_GenericElementInit PROTO (( jr_ESIS_GenericElementType * generic_info, char * name_str )); extern void jr_ESIS_GenericElementUndo PROTO (( jr_ESIS_GenericElementType * generic_info )); extern jr_int jr_ESIS_GenericElementHash PROTO (( const void * void_arg_1 )); extern jr_int jr_ESIS_GenericElementCmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); /******** Element ********/ extern void jr_ESIS_ElementInit PROTO (( jr_ESIS_ElementType * element_ptr, jr_ESIS_TreeType * esis_grove, jr_ESIS_ElementType * parent_element_ptr )); extern void jr_ESIS_ElementUndo PROTO (( jr_ESIS_ElementType * entity_info )); extern void jr_ESIS_ElementSetData PROTO (( jr_ESIS_ElementType * element_ptr, char * data_str )); extern void jr_ESIS_ElementAddAttribute PROTO (( jr_ESIS_ElementType * element_ptr, char * attr_name_str, char * attr_value_str )); extern void jr_ESIS_ElementAddSubElement PROTO (( jr_ESIS_ElementType * parent_element_ptr, jr_ESIS_ElementType * element_ptr )); /******** Index ********/ extern void jr_ESIS_IndexInit PROTO (( jr_ESIS_IndexType * esis_index, char * attr_name_str, char * opt_generic_name_str )); extern void jr_ESIS_IndexUndo PROTO (( jr_ESIS_IndexType * esis_index )); /******** Index Value ********/ extern void jr_ESIS_IndexValueInit PROTO (( jr_ESIS_IndexValueType * esis_index, char * attr_value_str )); extern void jr_ESIS_IndexValueUndo PROTO (( jr_ESIS_IndexValueType * esis_index_value )); extern jr_int jr_ESIS_IndexValueHash PROTO (( const void * void_arg_1 )); extern jr_int jr_ESIS_IndexValueCmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); /******** Element List ********/ extern void jr_ESIS_ElementListInit PROTO (( jr_ESIS_ElementList * element_list )); extern void jr_ESIS_ElementListUndo PROTO (( jr_ESIS_ElementList * element_list )); extern jr_ESIS_ElementType *jr_ESIS_ElementListNewElementPtr PROTO (( jr_ESIS_ElementList * element_list )); extern void jr_ESIS_GlobalElementListInit PROTO (( jr_ESIS_ElementList * element_list )); extern void jr_ESIS_GenericElementListInit PROTO (( jr_ESIS_ElementList * element_list )); extern void jr_ESIS_SubElementListInit PROTO (( jr_ESIS_ElementList * element_list )); extern void jr_ESIS_MatchingElementListInit PROTO (( jr_ESIS_ElementList * element_list )); #define jr_ESIS_ElementListAppendToTail(list, el_ptr) \ jr_LListAppendElement ( \ (list)->data_list, jr_LListTailPtr ((list)->data_list), el_ptr \ ) #define jr_ForEachESIS_ElementListPtr(list, el_ptr) \ jr_LListForEachElementPtr ((list)->data_list, el_ptr) /******* Element Stack ********/ extern void jr_ESIS_ElementStackInit PROTO (( jr_ESIS_ElementStack * element_stack )); extern void jr_ESIS_ElementStackUndo PROTO (( jr_ESIS_ElementStack * element_stack )); #endif
frankjas/libjr
libjr/io/pathdb.c
#include "ezport.h" #include <stdio.h> #include <errno.h> #include <string.h> #include "jr/apr.h" #include "jr/syscalls.h" #include "jr/io.h" #include "jr/alist.h" #include "jr/malloc.h" #include "jr/error.h" jr_int jr_PathDbMakePath ( const char * base_path, jr_int numeric_value, jr_int value_base, jr_int path_flags, const char ** balanced_path_ref, char * error_buf) { FILE * conf_fp = 0; jr_int conf_is_locked = 0; char * conf_path = 0; jr_int max_value = -1; char * balanced_path = 0; char * old_path = 0; char * new_path = 0; char * tmp_dir = 0; char * old_mod_path = 0; char * new_mod_path = 0; jr_int initialize_conf = 0; jr_dir_t dir_info[1]; jr_int curr_digit; jr_AList path_buf[1]; char digit_buf[32]; jr_int num_digits; jr_int max_num_digits; jr_int k; jr_int nitems; jr_int status; jr_AListInit (path_buf, sizeof (char)); jr_dir_init (dir_info); /* ** 11/26/06: Copy the base path to the char list (no null) */ for (k=0; base_path[k]; k++) { jr_AListNativeSetNewTail (path_buf, base_path[k], char); } if (jr_AListNativeTail (path_buf, char) == '/') { jr_AListDeleteTail (path_buf); } /* ** 11/26/05: Open and lock the conf file, reading the current maximum value */ conf_path = jr_malloc (strlen (base_path) + 1 + strlen (jr_PATH_DB_CONF_FILE) + 1); sprintf (conf_path, "%s/%s", base_path, jr_PATH_DB_CONF_FILE); conf_fp = fopen (conf_path, "r+"); if (conf_fp == 0 && errno == ENOENT) { conf_fp = fopen (conf_path, "w+"); } if (conf_fp == 0) { jr_esprintf (error_buf, "couldn't open '%.64s': %s", conf_path, strerror (errno)); status = jr_ConvertErrno (errno); goto return_status; } if (path_flags & jr_PATH_DB_CREATE_FLAG) { status = jr_FilePtrWriteLock (conf_fp, 5, error_buf); } else { status = jr_FilePtrReadLock (conf_fp, 5, error_buf); } if (status != 0) { jr_esprintf (error_buf, "couldn't lock '%.64s': %s", conf_path, strerror (errno)); goto return_status; } conf_is_locked = 1; max_value = -1; { char line_buffer[256]; fseek (conf_fp, 0, SEEK_SET); while (fgets (line_buffer, sizeof (line_buffer), conf_fp) != NULL) { nitems = sscanf (line_buffer, "max. value: %d", &max_value); if (nitems != 1) { jr_esprintf (error_buf, "badly formatted conf. file '%.64s'", conf_path); status = jr_INTERNAL_ERROR; goto return_status; } } } if (max_value < 0) { max_value = 0; initialize_conf = 1; } if (value_base > 36) { jr_esprintf (error_buf, "value base (%d) is too large, max. is 36", value_base); status = jr_INTERNAL_ERROR; goto return_status; } /* ** 11/26/05: figure out the digits in reverse order. */ { jr_int max_quotient; jr_int curr_quotient; max_quotient = max_value; curr_quotient = numeric_value; num_digits = 0; max_num_digits = 0; for (; max_quotient > 0 || curr_quotient > 0; num_digits++) { if (curr_quotient) { curr_digit = curr_quotient % value_base; } else { curr_digit = 0; } if (value_base <= 10) { digit_buf[num_digits] = '0' + curr_digit; } else { digit_buf[num_digits] = 'a' + curr_digit; } if (curr_quotient) { curr_quotient = curr_quotient / value_base; } if (max_quotient) { max_quotient = max_quotient / value_base; max_num_digits ++; } } if (max_value == 0 && numeric_value == 0) { digit_buf[num_digits] = '0'; num_digits++; } } /* ** 11/26/05: Add the digits to the char list, creating the desired path. */ for (k=num_digits - 1; k >= 0; k--) { curr_digit = digit_buf[k]; jr_AListNativeSetNewTail (path_buf, '/', char); jr_AListNativeSetNewTail (path_buf, curr_digit, char); } jr_AListNativeSetNewTail (path_buf, 0, char); balanced_path = jr_strdup (jr_AListHeadPtr (path_buf)); if (path_flags & jr_PATH_DB_CREATE_FLAG) { char * cptr; if (num_digits > max_num_digits && num_digits > 1) { jr_int num_new_levels = num_digits - max_num_digits; jr_int k; jr_int q; /* ** 1-18-2011: move the top-level directory/files down one level ** i.e. under a new top-level "0/" directory. Then keep adding ** levels until the right number of "0" levels are prepended. */ tmp_dir = jr_malloc (strlen (base_path) + 1 + 7 + 1); sprintf (tmp_dir, "%s/nXXXXXX", base_path); jr_MkTemp (tmp_dir); status = jr_MakeDirectoryPath (tmp_dir, jr_PERM_RWX_ALL, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't make temp. dir '%.64s': %s", tmp_dir, error_buf); goto return_status; } old_path = jr_malloc (strlen (base_path) + 1 + 1 + 1); new_path = jr_malloc (strlen (tmp_dir) + 1 + 1 + 1); for (k=0; k < num_new_levels; k++) { for (q=0; q < value_base; q++) { sprintf (old_path, "%s/%c", base_path, '0' + q); sprintf (new_path, "%s/%c", tmp_dir, '0' + q); status = jr_MovePath (old_path, new_path, error_buf); if (status != 0 && status != jr_NOT_FOUND_ERROR) { jr_esprintf (error_buf, "couldn't move '%.64s' to '%.64s': %s", old_path, new_path, error_buf ); goto return_status; } } if (max_num_digits == 1 && k == 0) { /* ** 1-18-2011: going from one digit to many, i.e. adding the first layer ** of directories. Move all the files in the current directory ** starting with old_path to the new '0' directory. ** Rationale: PathDb returns the old path and the caller may have ** appended other chars onto it. */ const char * entry_path; jr_int nitems; char first_char; status = jr_dir_open (dir_info, base_path, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't open '%.64s': %s", base_path, error_buf); goto return_status; } while (1) { status = jr_dir_read (dir_info, &entry_path, 0, error_buf); if (status != 0) { if (status == jr_NOT_FOUND_ERROR) { break; } goto return_status; } nitems = sscanf( entry_path, "%c", &first_char); if (nitems != 1) { continue; } if (first_char >= '0' && first_char <= '0' + value_base - 1) { if (old_mod_path) { jr_free( old_mod_path); } if (new_mod_path) { jr_free( new_mod_path); } old_mod_path = jr_malloc( strlen(base_path) + 1 + strlen(entry_path) + 1); new_mod_path = jr_malloc( strlen(tmp_dir) + 1 + strlen(entry_path) + 1); sprintf( old_mod_path, "%s/%s", base_path, entry_path); sprintf( new_mod_path, "%s/%s", tmp_dir, entry_path); status = jr_MovePath (old_mod_path, new_mod_path, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't move '%.64s' to '%.64s': %s", old_mod_path, new_mod_path, error_buf ); goto return_status; } } } } sprintf (new_path, "%s/0", base_path); status = jr_MovePath (tmp_dir, new_path, error_buf); if (status != 0 && status != jr_NOT_FOUND_ERROR) { jr_esprintf (error_buf, "couldn't move '%.64s' to '%.64s': %s", old_path, new_path, error_buf ); goto return_status; } } } if (path_flags & jr_PATH_DB_FILE_FLAG) { cptr = strrchr (balanced_path, '/'); if (cptr) { *cptr = 0; } } status = jr_MakeDirectoryPath (balanced_path, jr_PERM_RWX_ALL, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't make new path '%.64s': %s", tmp_dir, error_buf); goto return_status; } if (path_flags & jr_PATH_DB_FILE_FLAG) { if (cptr) { *cptr = '/'; } } if (numeric_value > max_value || initialize_conf) { fseek (conf_fp, 0, SEEK_SET); fprintf (conf_fp, "max. value: %d\n", numeric_value); } } status = 0; *balanced_path_ref = balanced_path; balanced_path = 0; return_status : { jr_AListUndo (path_buf); jr_dir_undo (dir_info); if (conf_path) { jr_free (conf_path); } if (conf_fp) { if (conf_is_locked) { jr_FilePtrUnLock (conf_fp); } fclose (conf_fp); } if (balanced_path) { jr_free (balanced_path); } if (tmp_dir) { jr_free (tmp_dir); } if (old_path) { jr_free (old_path); } if (new_path) { jr_free (new_path); } if (old_mod_path) { jr_free (old_mod_path); } if (new_mod_path) { jr_free (new_mod_path); } } return status; } #ifdef __garbage__ for (k=num_digits - 1; k >= 0; k--) { curr_digit = digit_buf[k]; jr_AListNativeSetNewTail (path_buf, '/', char); jr_AListNativeSetNewTail (path_buf, curr_digit, char); jr_AListNativeSetNewTail (path_buf, 0, char); status = jr_stat (jr_AListHeadPtr (path_buf), stat_info, error_buf); if (status == jr_NOT_FOUND_ERROR) { if (jr_path_flags & jr_PATH_DB_CREATE) { if (k != 0) { status = jr_MakeDirectoryPath (jr_AListHeadPtr (path_buf), error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't create dir '%.64s': %s", jr_AListHeadPtr (path_buf), error_buf ); goto return_status; } } } else { jr_esprintf (error_buf, "not found"); goto return_status; } } else if (status < 0) { jr_esprintf (error_buf, "couldn't access '%.64s': %s", jr_AListHeadPtr (path_buf), error_buf ); goto return_status; } else if (jr_stat_is_directory (stat_info)) { jr_AListDeleteTail (path_buf); /* ** 11/25/05: get rid of the null */ if (k == 0) { jr_AListNativeSetNewTail (path_buf, '/', char); jr_AListNativeSetNewTail (path_buf, 0, char); break; } /* ** 11/25/05: Traverse downwards */ } else { /* ** 11/26/05: The current path is a file */ if (k == 0) { if (path_flags & jr_PATH_DB_FILE_FLAG) { break; } jr_esprintf (error_buf, "desired path is not a directory (%.64s)", jr_AListHeadPtr (path_buf) ); status = -1; goto return_status; } if (path_flags & jr_PATH_DB_CREATE_FLAG) { /* ** 11/25/05: it's a file and this value has more digits, ** -> this value is greater than anything stored before */ if (open_flags & jr_PATH_DB_DIRECTORY_FLAG) { status = jr_MakeDirectoryPath ( jr_AListHeadPtr (path_buf), jr_PERMS_RWX_ALL, error_buf ); } continue; } } } #endif
frankjas/libjr
libjr/io/memfile.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <errno.h> #include <signal.h> #include "jr/syscalls.h" #include "jr/malloc.h" #include "jr/memfile.h" #include "jr/io.h" #include "jr/error.h" #ifndef has_broken_sigio_on_pipes #include <unistd.h> extern void jr_MemoryFileIO_Handler PROTO (( jr_int rfd, jr_MemoryFileType * mem_file_ptr )); jr_MemoryFileType *jr_MemoryFileCreateForWriting (max_buffer_size, error_buf) jr_int max_buffer_size; char * error_buf; { jr_MemoryFileType * mem_file_ptr = 0; jr_int fd_array[2]; jr_int status; /* * No Init() function, since we store the pointer to the struct * in the async handler support routines. */ mem_file_ptr = jr_malloc (sizeof (*mem_file_ptr)); memset (mem_file_ptr, 0, sizeof (*mem_file_ptr)); jr_AListInit (mem_file_ptr->char_buffer, sizeof (char)); mem_file_ptr->max_buffer_size = max_buffer_size; mem_file_ptr->rfd = -1; mem_file_ptr->wfd = -1; status = pipe (fd_array); if (status != 0) { jr_esprintf (error_buf, "couldn't get 'pipe': %s", strerror (errno)); status = -1; goto return_status; } mem_file_ptr->rfd = fd_array [0]; mem_file_ptr->wfd = fd_array [1]; mem_file_ptr->fp = fdopen (mem_file_ptr->wfd, "w"); if (mem_file_ptr->fp == NULL) { jr_esprintf (error_buf, "couldn't fdopen(%d): %s", mem_file_ptr->wfd, strerror (errno)); status = -1; goto return_status; } setvbuf (mem_file_ptr->fp, NULL, _IOLBF, 0); status = jr_FileDescInitNonBlockingIO (mem_file_ptr->rfd, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't init. non-blocking I/O: %s", error_buf); status = -1; goto return_status; } status = jr_FileDescInitReadAsyncIO ( mem_file_ptr->rfd, jr_MemoryFileIO_Handler, mem_file_ptr, error_buf ); if (status != 0) { jr_esprintf (error_buf, "couldn't init. async I/O: %s", error_buf); status = -1; goto return_status; } status = 0; return_status : { if (status != 0) { if (mem_file_ptr->rfd != -1) { close (mem_file_ptr->rfd); } if (mem_file_ptr->wfd != -1) { close (mem_file_ptr->wfd); } if (mem_file_ptr->fp) { fclose (mem_file_ptr->fp); } jr_AListUndo (mem_file_ptr->char_buffer); jr_free (mem_file_ptr); return 0; } } return mem_file_ptr; } const char *jr_MemoryFileOpenString (mem_file_ptr) jr_MemoryFileType * mem_file_ptr; { if (mem_file_ptr->old_mask_ptr == 0) { mem_file_ptr->old_mask_ptr = jr_malloc (sizeof (sigset_t)); mem_file_ptr->num_string_opens = 0; jr_BlockAsyncIO (mem_file_ptr->old_mask_ptr); } mem_file_ptr->num_string_opens ++; jr_AListNativeSetNewTail (mem_file_ptr->char_buffer, 0, char); jr_AListDeleteTail (mem_file_ptr->char_buffer); return jr_AListHeadPtr (mem_file_ptr->char_buffer); } void jr_MemoryFileCloseString (mem_file_ptr, string) jr_MemoryFileType * mem_file_ptr; const char * string; { mem_file_ptr->num_string_opens --; if (mem_file_ptr->num_string_opens == 0 && mem_file_ptr->old_mask_ptr) { jr_UnBlockAsyncIO (mem_file_ptr->old_mask_ptr); jr_free (mem_file_ptr->old_mask_ptr); mem_file_ptr->old_mask_ptr = 0; } } void jr_MemoryFileIO_Handler (rfd, mem_file_ptr) jr_int rfd; jr_MemoryFileType * mem_file_ptr; { jr_int read_size; jr_int status; while (1) { read_size = 8192; if ( mem_file_ptr->max_buffer_size == 0 || jr_AListSize (mem_file_ptr->char_buffer) < mem_file_ptr->max_buffer_size) { jr_AListIncreaseCapacity ( mem_file_ptr->char_buffer, jr_AListSize (mem_file_ptr->char_buffer) + read_size ); } else { jr_AListIncreaseCapacity ( mem_file_ptr->char_buffer, mem_file_ptr->max_buffer_size + read_size ); } status = read (rfd, jr_AListTailPtr (mem_file_ptr->char_buffer) + 1, read_size); if (status == 0) { mem_file_ptr->saw_eof = 1; break; } if (status < 0) { break ; } if ( mem_file_ptr->max_buffer_size == 0 || jr_AListSize (mem_file_ptr->char_buffer) + status < mem_file_ptr->max_buffer_size) { jr_AListSetSize ( mem_file_ptr->char_buffer, jr_AListSize (mem_file_ptr->char_buffer) + status ); } else { jr_AListSetSize (mem_file_ptr->char_buffer, mem_file_ptr->max_buffer_size); } } } #else /* * No asynchronous I/O on pipes. Use a temp file instead. */ jr_MemoryFileType *jr_MemoryFileCreateForWriting (max_buffer_size, error_buf) jr_int max_buffer_size; char * error_buf; { jr_MemoryFileType * mem_file_ptr = 0; const char * file_name; jr_int status; /* * No Init() function, since we store the pointer to the struct * in the async handler support routines. */ mem_file_ptr = jr_malloc (sizeof (*mem_file_ptr)); memset (mem_file_ptr, 0, sizeof (*mem_file_ptr)); jr_AListInit (mem_file_ptr->char_buffer, sizeof (char)); mem_file_ptr->max_buffer_size = max_buffer_size; mem_file_ptr->rfd = -1; mem_file_ptr->wfd = -1; file_name = "/tmp/j1XXXXXX"; if (strlen (file_name) + 1 > jr_MEM_FILE_TMP_BUF_LENGTH) { jr_esprintf (error_buf, "internal error: buffer length %d < file name length %d", jr_MEM_FILE_TMP_BUF_LENGTH, (jr_int) strlen (file_name) + 1 ); status = -1; goto return_status; } mem_file_ptr->fp = jr_TempFileOpen (0, error_buf); if (mem_file_ptr->fp == NULL) { status = -1; goto return_status; } status = 0; return_status : { if (status != 0) { if (mem_file_ptr->fp) { fclose (mem_file_ptr->fp); } jr_AListUndo (mem_file_ptr->char_buffer); jr_free (mem_file_ptr); mem_file_ptr = 0; } } return mem_file_ptr; } const char *jr_MemoryFileOpenString (mem_file_ptr) jr_MemoryFileType * mem_file_ptr; { char * string; unsigned jr_int string_length; fflush (mem_file_ptr->fp); fseek (mem_file_ptr->fp, 0, SEEK_SET); string = jr_FilePtrReadIntoNewMemory (mem_file_ptr->fp, &string_length); string[string_length] = 0; fseek (mem_file_ptr->fp, 0, SEEK_END); return string; } void jr_MemoryFileCloseString (mem_file_ptr, string) jr_MemoryFileType * mem_file_ptr; const char * string; { if (string) { jr_free (string); } } # endif void jr_MemoryFileDestroy (mem_file_ptr) jr_MemoryFileType * mem_file_ptr; { jr_AListUndo (mem_file_ptr->char_buffer); #ifndef has_broken_sigio_on_pipes if (mem_file_ptr->rfd >= 0) { jr_FileDescUndoNonBlockingIO (mem_file_ptr->rfd, 0); jr_FileDescUndoReadAsyncIO (mem_file_ptr->rfd, 0); close (mem_file_ptr->rfd); } if (mem_file_ptr->wfd >= 0) { close (mem_file_ptr->wfd); } #endif if (mem_file_ptr->fp) { fclose (mem_file_ptr->fp); } if (mem_file_ptr->old_mask_ptr) { jr_free (mem_file_ptr->old_mask_ptr); } jr_free (mem_file_ptr); }
frankjas/libjr
libjr/string/creplace.c
<gh_stars>0 #include "ezport.h" #include "jr/string.h" void jr_ReplaceAllOfChar(str,old,new) char *str ; jr_int old ; jr_int new ; { for (;*str;str++) { if (*str == old) *str = new ; } } /* void main() { char * original = " hello 12345 there 6" ; char * result ; jr_int old_char_val = 'e' ; jr_int new_char_val = 'E' ; s1 = jr_strdup(original) ; jr_ReplaceAllOfChar(result, old_char_val, new_char_val) ; fprintf(stdout, "jr_ReplaceAllOfChar(%s, '%c', '%c') == '%s'\n", original, old_char_val, new_char_val result ) ; jr_free(result) ; } */
frankjas/libjr
include/jr/test/shell.h
#ifndef __tstcmds_h___ #define __tstcmds_h___ #include "ezport.h" #include <stdio.h> #include <time.h> #include "jr/inputbuf.h" #include "jr/alist.h" #include "jr/htable.h" #include "jr/llist.h" typedef struct { jr_IB_InputBuffer input_buffer [1]; jr_AList command_list [1]; jr_int status; char * prompt_str; char * script_file; FILE * script_rfp; jr_int (*parse_fn) (); jr_int (*scan_fn) (); void (*var_undo_fn) (); void (*var_print_fn) (); jr_LList help_info_list [1]; jr_HTable variable_table [1]; jr_AList include_dir_list [1]; jr_int recursive_call; unsigned verbose : 1; unsigned save_command : 1; unsigned do_history : 1; unsigned quit : 1; unsigned echo : 1; unsigned break_on_bad_status : 1; unsigned save_file_commands : 1; unsigned continue_loop : 1; unsigned break_loop : 1; unsigned assert_next_is_bad : 1; unsigned check_malloc_bounds : 1; } jr_TestShellType ; extern void jr_TestShellInit PROTO (( jr_TestShellType * shell_info, jr_int (*parse_fn) (), jr_int (*scan_fn) (), void (*var_undo_fn) (), void (*var_print_fn) (), const char * prompt_str )); extern void jr_TestShellUndo PROTO (( jr_TestShellType * shell_info )); extern jr_int jr_TestShellReadFromFileName PROTO (( jr_TestShellType * shell_info, const char * file_name, char * error_buf )); extern jr_int jr_TestShellReadFromFilePtr PROTO (( jr_TestShellType * shell_info, FILE * rfp, const char * file_name, char * error_buf )); extern jr_int jr_TestShellRead PROTO (( jr_TestShellType * shell_info, char * error_buf )); extern jr_int jr_TestShellReadString PROTO (( jr_TestShellType * shell_info, char * input_string, char * error_buf )); extern void jr_TestShellSetFilePtr PROTO (( jr_TestShellType * shell_info, FILE * rfp, const char * file_name )); extern void jr_TestShellEmptyHistory PROTO (( jr_TestShellType * shell_info )); extern void jr_TestShellAddIncludeDir PROTO(( jr_TestShellType * shell_info, const char * include_dir )); extern jr_int jr_TestShellPushNewInputFile PROTO (( jr_TestShellType * shell_info, const char * file_name, char * error_buf )); extern void jr_TestShellSave PROTO (( jr_TestShellType * shell_info, FILE * wfp )); extern void jr_TestShellAddHelpMessage PROTO (( jr_TestShellType * shell_info, char * command_name, char * help_message )); extern void jr_TestShellPrintHelpMessage PROTO (( jr_TestShellType * shell_info, char * command_name, FILE * wfp )); extern void jr_TestShellAddStandardHelpMessages PROTO (( jr_TestShellType * shell_info )); extern void jr_TestShellBeforeRecursion PROTO (( jr_TestShellType * shell_info )); extern void jr_TestShellAfterRecursion PROTO (( jr_TestShellType * shell_info )); extern void jr_TestShellBreakPoint ( jr_TestShellType * shell_info, jr_int is_for_command); extern void jr_TestShellPrintLocation ( jr_TestShellType * shell_info, FILE * opt_wfp); typedef struct { char * line_str; unsigned save_command : 1; } jr_TestShellLineStruct; #define jr_TestShellIsVerbose(shell_info) ((shell_info)->verbose) #define jr_TestShellStatus(shell_info) ((shell_info)->status) #define jr_TestShellHasBadStatus(shell_info) ((shell_info)->status == -1) #define jr_TestShellQuit(shell_info) ((shell_info)->quit) #define jr_TestShellBreakLoop(shell_info) ((shell_info)->break_loop) #define jr_TestShellContinueLoop(shell_info) ((shell_info)->continue_loop) #define jr_TestShellInRecursion(shell_info) ((shell_info)->recursive_call) #define jr_TestShellEndRecursion(shell_info) ((shell_info)->end_recursion) #define jr_TestShellCheckMallocBounds(shell_info) ((shell_info)->check_malloc_bounds) #define jr_TestShellDontSaveCommand(shell_info) ((shell_info)->save_command = 0) #define jr_TestShellSetBadStatus(shell_info) ((shell_info)->status = -1) #define jr_TestShellSetQuit(shell_info, v) ((shell_info)->quit = (v) != 0) #define jr_TestShellSetBreakLoop(shell_info, v) ((shell_info)->break_loop = (v) != 0) #define jr_TestShellSetContinueLoop(shell_info, v) ((shell_info)->continue_loop = (v) != 0) #define jr_TestShellSetBreakOnBadStatus(shell_info, v) ((shell_info)->break_on_bad_status = (v) != 0) #define jr_TestShellSetEndRecursion(shell_info, v) ((shell_info)->end_recursion = (v) != 0) #define jr_TestShellSetCheckMallocBounds(shell_info, v) ((shell_info)->check_malloc_bounds = (v) != 0) #define jr_TestShellAssertNextCommandIsBad(shell_info) ((shell_info)->assert_next_is_bad = 1) #define jr_TestShellFileName(shell_info) \ jr_IB_CurrentContextName ((shell_info)->input_buffer) #define jr_TestShellFilePtr(shell_info) \ jr_IB_CurrentContextRfp ((shell_info)->input_buffer) #define jr_TestShellLineNumber(shell_info) \ (jr_IB_CurrentContextLine ((shell_info)->input_buffer) - 1) #define jr_TestShellIsInteractive(shell_info) \ (jr_IB_CurrentContextRfp ((shell_info)->input_buffer) == stdin) /******** Variable Support Functions ********/ typedef struct { const char * variable_name; jr_int token_number; const void * data_ptr; } jr_TestShellVarInfoType; extern void jr_TestShellSetVarInfo PROTO (( jr_TestShellType * shell_info, const char * var_name, jr_int token_number, const void * data_ptr )); extern jr_TestShellVarInfoType *jr_TestShellGetVarInfo PROTO (( jr_TestShellType * shell_info, const char * var_name )); extern void * jr_TestShellGetDataPtr PROTO (( jr_TestShellType * shell_info, const char * var_name )); #define jr_TestShellGetStringValue(shell_info, var_name) \ ((const char *)jr_TestShellGetDataPtr (shell_info, var_name)) extern jr_int jr_TestShellGetIntValue PROTO (( jr_TestShellType * shell_info, char * var_name, jr_int integer_tkn, jr_int ulong_tkn )); extern void jr_TestShellSetIntValue PROTO (( jr_TestShellType * shell_info, char * var_name, jr_int integer_tkn, jr_int value )); extern jr_int jr_TestShellDeleteVariable PROTO (( jr_TestShellType * shell_info, const char * var_name )); extern void * jr_TestShellExtractVariable PROTO (( jr_TestShellType * shell_info, const char * var_name )); extern void jr_TestShellPrintVariables PROTO (( jr_TestShellType * shell_info, jr_int is_diagnostic, FILE * wfp )); #define jr_TestShellVarDataUndo(shell_info, token_number, data_ptr) \ (*(shell_info)->var_undo_fn) (shell_info, token_number, data_ptr) #define jr_TestShellPrintVariable(shell_info, var_info, is_diagnostic, wfp) \ (*(shell_info)->var_print_fn) (shell_info, var_info, is_diagnostic, wfp) extern const char * jr_TestShellVarDataPtrName PROTO (( jr_TestShellType * shell_info, void * data_ptr )); extern void jr_TestShellDestroyIfNotVarDataPtr PROTO (( jr_TestShellType * shell_info, jr_int token_number, void * data_ptr )); extern jr_TestShellVarInfoType *jr_TestShellIsVarDataPtr PROTO (( jr_TestShellType * shell_info, void * data_ptr )); extern void jr_TestShellVarInfoInit PROTO (( jr_TestShellVarInfoType * var_info, const char * variable_name, jr_int token_number, const void * data_ptr )); extern void jr_TestShellVarInfoUndo PROTO (( jr_TestShellType * shell_info, jr_TestShellVarInfoType * var_info )); extern jr_int jr_TestShellVarInfoHash PROTO (( const void * void_arg_1 )); extern jr_int jr_TestShellVarInfoCmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); extern jr_int jr_TestShellVarInfoPtrCmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); #define jr_TestShellForEachVarInfoPtr(shell_info, var_info) \ jr_HTableForEachElementPtr ((shell_info)->variable_table, var_info) #define jr_TestShellVarInfoName(var_info) \ ((var_info)->variable_name) #define jr_TestShellVarInfoTokenNumber(var_info) \ ((var_info)->token_number) #define jr_TestShellVarInfoDataPtr(var_info) \ ((void *) ((var_info)->data_ptr)) #define jr_TestShellVarInfoSetDataPtr(var_info, v) \ ((var_info)->data_ptr = (v)) /******** Help Support ********/ typedef struct { char * command_name; char * help_message; } jr_TestShellHelpType; extern void jr_TestShellHelpInit PROTO (( jr_TestShellHelpType * help_info, char * command_name, char * help_message )); extern void jr_TestShellHelpUndo PROTO (( jr_TestShellHelpType * help_info )); #define jr_TestShellHelpCommandName(help_info) ((help_info)->command_name) #define jr_TestShellHelpMessage(help_info) ((help_info)->help_message) extern void jr_TestShellAddExpressionHelpMessages PROTO (( jr_TestShellType * shell_info )); /******** Inet Interfaces ********/ typedef struct { const char * host_name; jr_int port_number; jr_int max_msg_size; jr_int max_bits_per_second; } jr_TestInterfaceType; extern void jr_TestInterfaceInit( jr_TestInterfaceType * interface_ptr, const char * host_name, jr_int port_number, jr_int max_msg_size, jr_int max_bits_per_second); extern void jr_TestInterfaceUndo( jr_TestInterfaceType * interface_ptr); #define jr_TestInterfaceHostName( interface_ptr) ((interface_ptr)->host_name) #define jr_TestInterfacePortNumber( interface_ptr) ((interface_ptr)->port_number) #define jr_TestInterfaceMaxMsgSize( interface_ptr) ((interface_ptr)->max_msg_size) #define jr_TestInterfaceMaxBitsPerSecond( interface_ptr) ((interface_ptr)->max_bits_per_second) #endif
frankjas/libjr
libjr/syscalls/jr_flock.c
#include "ezport.h" #include <apr-1/apr_pools.h> #include <apr-1/apr_file_io.h> #include <setjmp.h> #include "jr/apr.h" #include "jr/error.h" jr_int jr_file_lock ( jr_file_t * file_info, jr_int lock_type, jr_int time_out, char * error_buf) { jr_int status; if (time_out > 0) { /* ** 1/29/07: Don't have a usable timer mechanism, or signals with longjmp capabilities ** under win32. */ jr_esprintf (error_buf, "blocking, timed locks not supported"); status = jr_INTERNAL_ERROR; goto return_status; } else { /* * try a non-blocking lock */ jr_int apr_type; if (lock_type == jr_FILE_LOCK_WRITE) { apr_type = APR_FLOCK_EXCLUSIVE | APR_FLOCK_NONBLOCK; } else { apr_type = APR_FLOCK_SHARED | APR_FLOCK_NONBLOCK; } status = apr_file_lock (file_info->apr_file_ptr, apr_type); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } } status = 0; return_status : { } return status; } jr_int jr_file_unlock ( jr_file_t * file_info, char * error_buf) { jr_int status; status = apr_file_unlock (file_info->apr_file_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; }
frankjas/libjr
libjr/misc/coredump.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <string.h> #include <signal.h> #include <stdlib.h> #ifndef missing_unistd_h #include <unistd.h> #endif #include "jr/misc.h" #include "jr/syscalls.h" void jr_coredump () { /* ** 3/2/07: Can't do a malloc(), since called from inside jr_MallocDiag() code */ fflush(stdout); fflush(stderr); abort(); # ifdef SIGTRAP kill(getpid(), SIGTRAP); pause (); # endif } void jr_debugger_trap () { fflush(stdout); fflush(stderr); # if defined(ostype_winnt) __debugbreak(); /* ** 6-8-2011: Could also use DebugBreak(), but that requires ** linking to Kernel32.lib */ # elif defined(SIGTRAP) kill(getpid(), SIGTRAP); # else abort (); # endif } char jr_DiagFileDirectory[256]; char *jr_MakeDiagFileName (diag_file_buf, diag_file_buf_size, file_name) char * diag_file_buf; jr_int diag_file_buf_size; const char * file_name; { /* * Can't do dynamic allocation, since this function is used * as part of the resource allocation bookkeeping. */ jr_int str_length; jr_int copy_length; jr_int curr_length = 0; if (jr_DiagFileDirectory[0]) { str_length = (jr_int) strlen (jr_DiagFileDirectory); if (diag_file_buf_size - 1 - curr_length > str_length) { copy_length = str_length; } else { copy_length = diag_file_buf_size - 1 - curr_length; } if (copy_length > 0) { strncpy (diag_file_buf + curr_length, jr_DiagFileDirectory, copy_length + 1); curr_length += copy_length; } if (curr_length < diag_file_buf_size - 1) { diag_file_buf[curr_length++] = '/'; } } str_length = (jr_int) strlen (file_name); if (diag_file_buf_size - 1 - curr_length > str_length) { copy_length = str_length; } else { copy_length = diag_file_buf_size - 1 - curr_length; } if (copy_length > 0) { strncpy (diag_file_buf + curr_length, file_name, copy_length + 1); curr_length += copy_length; } diag_file_buf[curr_length] = 0; return diag_file_buf; }
frankjas/libjr
libjr/symtab/st_list.c
<reponame>frankjas/libjr #include "project.h" jr_int jr_ST_FieldListAddField ( list, str, storage_class, user_storage_sym, user_qualifier_sym, base_sym, num_stars, array, bit_field_value, bit_field_expr ) jr_ST_FieldList * list; char * str; jr_int storage_class; jr_ST_Symbol * user_storage_sym; jr_ST_Symbol * user_qualifier_sym; jr_ST_Symbol * base_sym; jr_int num_stars; jr_ST_ArrayList * array; jr_int bit_field_value; jr_C_ExprNodeType * bit_field_expr; { jr_ST_FieldType *field; if (*str) { jr_ST_FieldListForEachElementPtr (list, field) { if (strcmp (str, jr_ST_IdentifierStr (field->id)) == 0) { return (-1); } } } field = jr_AListNewTailPtr (list); memset (field + 1, 0, jr_AListElementSize (list) - sizeof (jr_ST_FieldType)); jr_ST_FieldInit ( field, str, storage_class, user_storage_sym, user_qualifier_sym, base_sym, num_stars, array, bit_field_value, bit_field_expr ); return (jr_AListTailIndex (list)); } void jr_ST_FieldListDestroy (list) jr_ST_FieldList *list; { jr_ST_FieldListUndo (list); jr_free (list); } void jr_ST_FieldListUndo (list) jr_ST_FieldList *list; { jr_ST_FieldType *field; jr_ST_FieldListForEachElementPtr (list, field) { jr_ST_FieldUndo (field); } jr_AListUndo (list); } void jr_ST_FieldInit ( field, str, storage_class, user_storage_sym, user_qualifier_sym, base_sym, num_stars, array, bit_field_value, bit_field_expr ) jr_ST_FieldType * field; char * str; jr_int storage_class; jr_ST_Symbol * user_storage_sym; jr_ST_Symbol * user_qualifier_sym; jr_ST_Symbol * base_sym; jr_int num_stars; jr_ST_ArrayList * array; jr_int bit_field_value; jr_C_ExprNodeType * bit_field_expr; { memset (field, 0, sizeof (jr_ST_FieldType)); field->id = jr_ST_IdentifierCreate (str); field->type = jr_ST_TypeCreate (jr_ST_VARIABLE, base_sym, num_stars, array); /* * this type is only good as long as the base symbol is good */ field->storage_class = storage_class; field->user_storage_sym = user_storage_sym; field->user_qualifier_sym = user_qualifier_sym; field->bit_field_value = bit_field_value; if (bit_field_expr) { field->bit_field_expr = jr_C_ExprNodeCreateCopy (bit_field_expr); } field->file_name = "unknown"; } void jr_ST_FieldUndo (field) jr_ST_FieldType * field; { if (! jr_ST_IdentifierIsInUse (field->id)) { jr_ST_IdentifierDestroy (field->id); } if (! jr_ST_TypeIsInUse (field->type)) { jr_ST_TypeDestroy (field->type); } if (field->bit_field_expr) { jr_C_ExprNodeDestroy (field->bit_field_expr); } } void jr_ST_FieldSetBitFieldExpr (field, length_expr) jr_ST_FieldType * field; jr_C_ExprNodeType * length_expr; { if (field->bit_field_expr) { jr_C_ExprNodeDestroy (field->bit_field_expr); } field->bit_field_expr = jr_C_ExprNodeCreateCopy (length_expr); } jr_int jr_ST_FieldCmp (field1, field2) jr_ST_FieldType * field1; jr_ST_FieldType * field2; { jr_int diff; diff = strcmp (jr_ST_FieldStr (field1), jr_ST_FieldStr (field2)); if (diff != 0) { return diff; } diff = field1->storage_class - field2->storage_class; if (diff != 0) { return diff; } diff = field1->user_storage_sym - field2->user_storage_sym; if (diff != 0) { return diff; } diff = field1->user_qualifier_sym - field2->user_qualifier_sym; if (diff != 0) { return diff; } diff = field1->bit_field_value - field2->bit_field_value; if (diff != 0) { return diff; } diff = jr_ST_TypeCmp (jr_ST_FieldTypePtr (field1), jr_ST_FieldTypePtr (field2)); if (diff != 0) { return diff; } return 0; } jr_int jr_ST_EnumListAddEnum (list, str, enum_value, value_expr) jr_ST_EnumList * list; char * str; jr_int enum_value; jr_C_ExprNodeType * value_expr; { jr_ST_EnumType *enum_ptr; jr_ST_EnumListForEachElementPtr (list, enum_ptr) { if (strcmp (str, jr_ST_EnumStr (enum_ptr)) == 0) { return (-1); } } enum_ptr = jr_AListNewTailPtr (list); enum_ptr->id = jr_ST_IdentifierCreate (str); enum_ptr->enum_value = enum_value; if (value_expr) { enum_ptr->value_expr = jr_C_ExprNodeCreateCopy (value_expr); } else { enum_ptr->value_expr = 0; } return 0; } void jr_ST_EnumListDestroy (list) jr_ST_EnumList *list; { jr_ST_EnumListUndo (list); jr_free (list); } void jr_ST_EnumListUndo (list) jr_ST_EnumList *list; { jr_ST_EnumType *enum_ptr; jr_ST_EnumListForEachElementPtr (list, enum_ptr) { if (! jr_ST_IdentifierIsInUse (enum_ptr->id)) { jr_ST_IdentifierDestroy (enum_ptr->id); } /* * if the id num or type num is non-zero, then * these ids and types are in id/type tables * and they shouldn't be jr_freed */ if (enum_ptr->value_expr) { jr_C_ExprNodeDestroy (enum_ptr->value_expr); } } jr_AListUndo (list); } jr_int jr_ST_ArrayListAddDimension (list, length_num, length_str, length_expr) jr_AList * list; jr_int length_num; char * length_str; jr_C_ExprNodeType * length_expr; { jr_ST_ArrayDimension *new_dimension; new_dimension = jr_AListNewTailPtr (list); new_dimension->length_num = length_num; if (length_str) { new_dimension->length_str = jr_strdup (length_str); } else { new_dimension->length_str = 0; } if (length_expr) { new_dimension->length_expr = jr_C_ExprNodeCreateCopy (length_expr); } else { new_dimension->length_expr = 0; } return (jr_AListTailIndex (list)); } void jr_ST_ArrayListDestroyLengthStrings (list) jr_AList *list; { jr_ST_ArrayDimension *curr_dimension; jr_AListForEachElementPtr (list, curr_dimension) { if (curr_dimension->length_str) { jr_free (curr_dimension->length_str); } if (curr_dimension->length_expr) { jr_C_ExprNodeDestroy (curr_dimension->length_expr); } } } void jr_ST_ArrayListDestroy (list) jr_AList *list; { jr_ST_ArrayListDestroyLengthStrings (list); jr_AListDestroy (list); } void jr_ST_ArrayListUndo (list) jr_AList *list; { jr_ST_ArrayListDestroyLengthStrings (list); jr_AListUndo (list); } void jr_ST_ArrayListInitCopy (dest_list, src_list) jr_AList * dest_list; jr_AList * src_list; { jr_int i; jr_ST_ArrayListInit (dest_list); jr_ST_ArrayForEachDimension (src_list, i) { jr_ST_ArrayListAddDimension ( dest_list, jr_ST_ArrayDimensionLengthNum (src_list, i), jr_ST_ArrayDimensionLengthStr (src_list, i), jr_ST_ArrayDimensionLengthExpr (src_list, i) ); } } jr_AList *jr_ST_ArrayListCreateCopy (src_list) jr_AList * src_list; { jr_AList * dest_list; dest_list = jr_malloc (sizeof (*dest_list)); jr_ST_ArrayListInitCopy (dest_list, src_list); return dest_list; }
frankjas/libjr
libjr/syscalls/jr_user.c
#include "ezport.h" #include <apr-1/apr_user.h> #include "jr/apr.h" #include "jr/error.h" #include "jr/malloc.h" void jr_uid_init ( jr_uid_t * uid_ptr) { memset (uid_ptr, 0, sizeof (*uid_ptr)); } void jr_uid_undo ( jr_uid_t * uid_ptr) { apr_pool_t * apr_pool_ptr = uid_ptr->apr_pool_ptr; if (apr_pool_ptr) { apr_pool_destroy (apr_pool_ptr); } } void jr_gid_init ( jr_gid_t * gid_ptr) { memset (gid_ptr, 0, sizeof (*gid_ptr)); } void jr_gid_undo ( jr_gid_t * gid_ptr) { apr_pool_t * apr_pool_ptr = gid_ptr->apr_pool_ptr; if (apr_pool_ptr) { apr_pool_destroy (apr_pool_ptr); } } jr_int jr_uid_init_current ( jr_uid_t * uid_ptr, char * error_buf) { apr_uid_t apr_uid_val; apr_gid_t apr_gid_val; apr_pool_t * apr_pool_ptr = 0; jr_int status; jr_uid_init (uid_ptr); jr_apr_initialize(); apr_pool_create (&apr_pool_ptr, NULL); status = apr_uid_current (&apr_uid_val, &apr_gid_val, apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } uid_ptr->id_value = apr_uid_val; uid_ptr->apr_pool_ptr = apr_pool_ptr; apr_pool_ptr = 0; status = 0; return_status : { if (apr_pool_ptr) { apr_pool_destroy (apr_pool_ptr); } } return status; } jr_int jr_uid_init_from_name ( jr_uid_t * uid_ptr, const char * user_name, char * error_buf) { apr_uid_t apr_uid_val; apr_gid_t apr_gid_val; apr_pool_t * apr_pool_ptr = 0; jr_int status; jr_uid_init (uid_ptr); jr_apr_initialize(); apr_pool_create (&apr_pool_ptr, NULL); status = apr_uid_get (&apr_uid_val, &apr_gid_val, user_name, apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } uid_ptr->id_value = apr_uid_val; uid_ptr->apr_pool_ptr = apr_pool_ptr; apr_pool_ptr = 0; status = 0; return_status : { if (apr_pool_ptr) { apr_pool_destroy (apr_pool_ptr); } } return status; } jr_int jr_gid_init_current ( jr_gid_t * gid_ptr, char * error_buf) { apr_uid_t apr_uid_val; apr_gid_t apr_gid_val; apr_pool_t * apr_pool_ptr = 0; jr_int status; jr_gid_init (gid_ptr); jr_apr_initialize(); apr_pool_create (&apr_pool_ptr, NULL); status = apr_uid_current (&apr_uid_val, &apr_gid_val, apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } gid_ptr->id_value = apr_gid_val; gid_ptr->apr_pool_ptr = apr_pool_ptr; apr_pool_ptr = 0; status = 0; return_status : { if (apr_pool_ptr) { apr_pool_destroy (apr_pool_ptr); } } return status; } jr_int jr_gid_init_from_name ( jr_gid_t * gid_ptr, const char * group_name, char * error_buf) { apr_gid_t apr_gid_val; apr_pool_t * apr_pool_ptr = 0; jr_int status; jr_gid_init (gid_ptr); jr_apr_initialize(); apr_pool_create (&apr_pool_ptr, NULL); status = apr_gid_get (&apr_gid_val, group_name, apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } gid_ptr->id_value = apr_gid_val; gid_ptr->apr_pool_ptr = apr_pool_ptr; status = 0; return_status : { if (apr_pool_ptr) { apr_pool_destroy (apr_pool_ptr); } } return status; } jr_int jr_uid_get_name ( jr_uid_t * uid_ptr, const char ** user_name_ref, char * error_buf) { apr_uid_t apr_uid_val = uid_ptr->id_value; apr_pool_t * apr_pool_ptr = uid_ptr->apr_pool_ptr; char * user_name; jr_int status; status = apr_uid_name_get (&user_name, apr_uid_val, apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } *user_name_ref = jr_strdup (user_name); status = 0; return_status : { } return status; } jr_int jr_gid_get_name ( jr_gid_t * gid_ptr, const char ** group_name_ref, char * error_buf) { apr_gid_t apr_gid_val = gid_ptr->id_value; apr_pool_t * apr_pool_ptr = gid_ptr->apr_pool_ptr; char * group_name; jr_int status; status = apr_gid_name_get (&group_name, apr_gid_val, apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } *group_name_ref = jr_strdup (group_name); status = 0; return_status : { } return status; } jr_int jr_uid_cmp ( const void * void_ptr_1, const void * void_ptr_2) { const jr_uid_t * uid_ptr_1 = void_ptr_1; const jr_uid_t * uid_ptr_2 = void_ptr_2; apr_uid_t apr_uid_val_1 = uid_ptr_1->id_value; apr_uid_t apr_uid_val_2 = uid_ptr_2->id_value; jr_int diff; diff = apr_uid_compare (apr_uid_val_1, apr_uid_val_2); if (diff != 0) { return diff; } return 0; } jr_int jr_gid_cmp ( const void * void_ptr_1, const void * void_ptr_2) { const jr_gid_t * gid_ptr_1 = void_ptr_1; const jr_gid_t * gid_ptr_2 = void_ptr_2; apr_gid_t apr_gid_val_1 = gid_ptr_1->id_value; apr_gid_t apr_gid_val_2 = gid_ptr_2->id_value; jr_int diff; diff = apr_gid_compare (apr_gid_val_1, apr_gid_val_2); if (diff != 0) { return diff; } return 0; }
frankjas/libjr
libjr/avl_tree/avl_prnt.c
#include "project.h" void jr_AVL_TreePrint (avl_tree, wfp, print_node_fn, print_width) jr_AVL_Tree * avl_tree; FILE * wfp; void (*print_node_fn) (); jr_int print_width; { void ** node_array; jr_int max_height; jr_int max_num_leaves; jr_int leaf_index, array_index; jr_int curr_height; jr_int remainder; if (jr_AVL_TreeIsEmpty (avl_tree)) { return; } /* * height of 0 is root with no children * the width of the bottom is 2^(max_height) */ max_height = jr_AVL_TreeElementHeight (avl_tree, jr_AVL_TreeRootPtr (avl_tree)); max_num_leaves = jr_get2power (max_height); /* * load up the node array */ node_array = jr_AVL_TreeToElementArray (avl_tree); /* * each leaf gets a row */ for (leaf_index = 0; leaf_index < max_num_leaves; leaf_index++) { /* * for each level, decide whether to print that level */ for (curr_height = 0; curr_height <= max_height; curr_height++) { if (curr_height > 0) { /* * if you draw a tree on its side * you see why this remainder when moding by * get2power (curr_height) gives you the correct * line to print 0 1 x 2 x 3 x 4 x 5 x 6 x 7 x * */ remainder = jr_get2power (curr_height - 1); } else { remainder = 0; } array_index = jr_get2power (max_height - curr_height); array_index += leaf_index / jr_get2power (curr_height); array_index -= 1; /* * flip curr_height so it is 0 for the root, 1 for the next * and max_height for the leaves, that gives the correct * starting index, 1 or 2, or three (if you index from 1). * Add which sibling of that level, gotten by the div, * subtract 1 since the array is indexed from 0. * * level * 0 1 1 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 * 1 2 3 4 5 6 7 8 9 .... * index */ if ( leaf_index % jr_get2power (curr_height) == (unsigned) remainder && node_array [array_index] != 0) { /* * if there is an item in the path, print it out, otherwise print a blank */ print_node_fn (node_array [array_index], wfp); putchar (' '); } else { jr_int i; for (i = 0; i < print_width; i++) { putchar (' '); } putchar (' '); } } putchar ('\n'); } jr_free (node_array); } void **jr_AVL_TreeToElementArray (avl_tree) jr_AVL_Tree * avl_tree; { void ** node_array; jr_int max_height, max_num_leaves; max_height = jr_AVL_TreeElementHeight (avl_tree, jr_AVL_TreeRootPtr (avl_tree)); max_num_leaves = jr_get2power (max_height); node_array = jr_malloc (2 * max_num_leaves * sizeof (void *)); memset (node_array, 0, 2 * max_num_leaves * sizeof (void *)); jr_AVL_TreeTraverseForElementArray (avl_tree, jr_AVL_TreeRootPtr (avl_tree), node_array, 0); return (node_array); } void jr_AVL_TreeTraverseForElementArray (avl_tree, node, node_array, array_index) jr_AVL_Tree * avl_tree; const void * node ; void ** node_array; jr_int array_index; { if (! node) return ; node_array [array_index] = (void *) node; if (jr_AVL_TreeLeftChildPtr (avl_tree, node)) { jr_AVL_TreeTraverseForElementArray( avl_tree, jr_AVL_TreeLeftChildPtr (avl_tree, node), node_array, 2 * array_index + 1 ) ; } if (jr_AVL_TreeRightChildPtr (avl_tree, node)) { jr_AVL_TreeTraverseForElementArray( avl_tree, jr_AVL_TreeRightChildPtr (avl_tree, node), node_array, 2 * array_index + 2 ) ; } } /* * for use in the debugger */ void jr_AVL_TreePrintElement (avl_tree, node) jr_AVL_Tree * avl_tree; const void * node; { fprintf (stderr, "node %p: left %p, right %p, height %d\n", node, jr_AVL_TreeLeftChildPtr (avl_tree, node), jr_AVL_TreeRightChildPtr (avl_tree, node), jr_AVL_TreeElementHeight (avl_tree, node) ); }
frankjas/libjr
libjr/string/envget.c
<reponame>frankjas/libjr<gh_stars>0 #include "ezport.h" #include <stdio.h> #include <string.h> #include "jr/string.h" #include "jr/malloc.h" extern char **environ ; jr_int jr_getenv_index(vector, name) char ** vector ; const char * name ; { char ** vp ; char * rhs_ptr ; jr_int diff ; jr_int i ; i = 0 ; for (vp = vector ; *vp; vp++, i++) { rhs_ptr = strchr(*vp, '=') ; if (rhs_ptr) rhs_ptr++ ; /* special style of strcmp which stops on null or '=' */ { const char * s1 = *vp ; const char * s2 = name ; for (; *s1 == *s2; s1++, s2++) { if (*s2 == 0) break ; if (*s1 == '=') break ; } if ((*s2 == 0) && (*s1 == '=')) diff = 0 ; else diff = *s1 - *s2 ; } if (diff == 0) { return(i) ; } } return(-1) ; } char *jr_getenv(vector, name) char ** vector ; const char * name ; { char ** vp ; char * rhs_ptr ; jr_int diff ; for (vp = vector ; *vp; vp++) { rhs_ptr = strchr(*vp, '=') ; if (rhs_ptr) rhs_ptr++ ; /* special style of strcmp which stops on null or '=' */ { const char * s1 = *vp ; const char * s2 = name ; for (; *s1 == *s2; s1++, s2++) { if (*s2 == 0) break ; if (*s1 == '=') break ; } if ((*s2 == 0) && (*s1 == '=')) diff = 0 ; else diff = *s1 - *s2 ; } if (diff == 0) { return(rhs_ptr) ; } } return(0) ; } /* test program is testenv.c */
frankjas/libjr
libjr/misc/cmpalwys.c
<gh_stars>0 #include "jr/misc.h" jr_int jr_always_true_cmp() { return(1) ; } jr_int jr_always_false_cmp() { return(0) ; }
frankjas/libjr
libjr/io/mailproj.h
#ifndef __mailproj_h___ #define __mailproj_h___ #define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <unistd.h> #include "jr/io.h" #include "jr/inetlib.h" #include "jr/mail.h" #include "jr/error.h" #define SMTP_PORT 25 #define SMTP_INIT_STATUS 220 #define SMTP_OK_STATUS 250 #define SMTP_WILL_FORWARD_STATUS 251 #define SMTP_QUIT_OK_STATUS 221 #define SMTP_DATA_OK_STATUS 354 #define SMTP_MAX_RESPONSE_LENGTH 2048 #endif
frankjas/libjr
libjr/syscalls/jr_mutex_unix.c
#include "ezport.h" /* ** 3/9/07: in case ostype_winnt is defined in ezport.h */ #ifndef ostype_winnt #include <pthread.h> #include <stdlib.h> #include <string.h> #include "jr/apr.h" #if jr_SIZEOF_PTHREAD_MUTEX_T < __SIZEOF_PTHREAD_MUTEX_T /* ** 3/2/07: verify declaration assumptions */ # error jr_SIZEOF_PTHREAD_MUTEX_T < __SIZEOF_PTHREAD_MUTEX_T #endif void jr_mutex_init ( jr_mutex_t * mutex_ptr, jr_int is_recursive) { pthread_mutex_t * pthread_mutex_ptr = (void *) mutex_ptr->arch_data.pthread_data; pthread_mutexattr_t attr[1]; pthread_mutexattr_init (attr); if (is_recursive) { pthread_mutexattr_settype (attr, PTHREAD_MUTEX_RECURSIVE); } else { # ifdef PTHREAD_MUTEX_FAST_NP pthread_mutexattr_settype (attr, PTHREAD_MUTEX_FAST_NP); # else pthread_mutexattr_settype (attr, PTHREAD_MUTEX_NORMAL); # endif } pthread_mutex_init (pthread_mutex_ptr, attr); pthread_mutexattr_destroy (attr); mutex_ptr->is_recursive = is_recursive != 0; } void jr_mutex_undo (mutex_ptr) jr_mutex_t * mutex_ptr; { pthread_mutex_t * pthread_mutex_ptr = (void *) mutex_ptr->arch_data.pthread_data; pthread_mutex_destroy (pthread_mutex_ptr); } void jr_mutex_lock (mutex_ptr) jr_mutex_t * mutex_ptr; { pthread_mutex_t * pthread_mutex_ptr = (void *) mutex_ptr->arch_data.pthread_data; pthread_mutex_lock (pthread_mutex_ptr); } void jr_mutex_unlock (mutex_ptr) jr_mutex_t * mutex_ptr; { pthread_mutex_t * pthread_mutex_ptr = (void *) mutex_ptr->arch_data.pthread_data; pthread_mutex_unlock (pthread_mutex_ptr); } jr_int jr_thread_once_cmp( const void *void_ptr_1, const void *void_ptr_2) { const jr_thread_once_t * once_ptr_1 = void_ptr_1; const jr_thread_once_t * once_ptr_2 = void_ptr_2; #if defined(ostype_cygwin) if (once_ptr_1->control_value.mutex != once_ptr_2->control_value.mutex) { return 1; } if (once_ptr_1->control_value.state != once_ptr_2->control_value.state) { return 1; } #elif defined(ostype_macosx) if (once_ptr_1->control_value.__sig != once_ptr_2->control_value.__sig) { return 1; } if (memcmp( once_ptr_1->control_value.__opaque, once_ptr_2->control_value.__opaque, jr_THREAD_OSX_ONCE_SIZE ) != 0) { return 1; } #else if (once_ptr_1->control_value != once_ptr_2->control_value) { return 1; } #endif return 0; } /* ** 3/2/07: verify that the declaration macro is syntactically valid */ jr_thread_once_declare_and_init (TestControl); #if defined(ostype_cygwin) || defined(ostype_sunos) || defined(ostype_macosx) void jr_thread_once_call ( jr_thread_once_t * once_control_ptr, void (*some_func)()) { pthread_once_t tmp_once_value = PTHREAD_ONCE_INIT; if (jr_thread_once_cmp (&tmp_once_value, &TestControl) != 0) { /* ** 3/15/07: make sure jr_thread_once_declare_and_init() is properly defined, ** since it uses hardcoded values to remove the include dependency on pthread.h ** (which only exists under some versions of Unix) */ abort(); } pthread_once ((void*) &once_control_ptr->control_value, some_func); } #else void jr_thread_once_call ( jr_thread_once_t * once_control_ptr, void (*some_func)()) { if (PTHREAD_ONCE_INIT != 0) { abort(); TestControl.control_value = 0; /* 3/2/07: shutup compiler warning */ } pthread_once (&once_control_ptr->control_value, some_func); } #endif #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/misc/memscoot.c
<gh_stars>0 #include "ezport.h" #include <stdint.h> #include "jr/misc.h" void jr_memscoot (buffer_arg, buffer_size, hole_offset, hole_size) void *buffer_arg; jr_int buffer_size; jr_int hole_offset; jr_int hole_size; { char * buffer = buffer_arg ; char * scoot_end; jr_int scoot_size; jr_int * int_scoot_end; jr_int int_scoot_size; jr_int int_hole_size; jr_int i ; scoot_end = buffer + buffer_size; scoot_size = buffer_size - hole_offset; if (hole_size % sizeof (jr_int)) { /* * its an odd # of bytes to open, do it character by character for simplicity */ for (i = 0; i < scoot_size; i++, scoot_end--) { scoot_end [hole_size - 1] = scoot_end [-1]; } return; } /* * hole size is word multiple * scoot until scoot_end is on a word boundary */ for (i = 0; i < scoot_size && (intptr_t) scoot_end % sizeof (jr_int) != 0; i++, scoot_end--) { if ((intptr_t) scoot_end % sizeof (jr_int) == 0) { /* * the end of the section to be copied is on a word boundary */ break; } scoot_end [hole_size - 1] = scoot_end [-1]; } /* * have scoot_size - i left to scoot */ int_scoot_end = (jr_int *) scoot_end; int_scoot_size = (scoot_size - i) / sizeof (jr_int); int_hole_size = hole_size / sizeof (jr_int); scoot_size = (scoot_size - i) % sizeof (jr_int); for (i = 0; i < int_scoot_size; i++, int_scoot_end--) { int_scoot_end [int_hole_size - 1] = int_scoot_end [-1]; } scoot_end = (char *) int_scoot_end; for (i = 0; i < scoot_size; i++, scoot_end--) { scoot_end [hole_size - 1] = scoot_end [-1]; } }
frankjas/libjr
libjr/syscalls/timedio.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <setjmp.h> #include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "jr/syscalls.h" static sigjmp_buf JumpBuffer ; static void local_alarm_handler(signum) jr_int signum ; { siglongjmp (JumpBuffer , 17) ; } /* .bp */ jr_int jr_Timed_fgets (buffer, length, rfp, seconds) char * buffer; jr_int length; FILE * rfp ; jr_int seconds ; { struct sigaction new_action[1]; struct sigaction old_action[1]; jr_int prev_alarm_time = 0 ; /* to shutup 'uninit.' msg */ jr_int timed_out; jr_int jmpval; char * status = NULL; /* to shutup 'uninit.' msg */ if ((jmpval = sigsetjmp(JumpBuffer, 1)) == 0) { new_action->sa_handler = local_alarm_handler; sigemptyset (&new_action->sa_mask); new_action->sa_flags = SA_RESTART; prev_alarm_time = alarm(0); sigaction (SIGALRM, new_action, old_action) ; alarm (seconds); /* timed work */ status = fgets (buffer , length , rfp); timed_out = 0; } else { timed_out = 1; } /* reset the old alarm and handler */ alarm (0); sigaction(SIGALRM , old_action , 0) ; alarm(prev_alarm_time) ; if (timed_out) { return -2; } if (status == NULL) { return -1; } return 0; }
frankjas/libjr
libjr/string/envset.c
#include "ezport.h" #include <stdio.h> #include <string.h> #include "jr/vector.h" #include "jr/malloc.h" extern char **environ ; char **jr_setenv(old_vector, name, new_rhs_value, old_entry_holder) char ** old_vector ; const char * name ; const char * new_rhs_value ; char ** old_entry_holder ; { jr_int name_len = (jr_int) strlen(name) ; jr_int value_len = (jr_int) strlen(new_rhs_value) ; char *new_entry = jr_malloc(value_len + name_len + 2) ; char *old_rhs_value = jr_getenv(old_vector, name) ; jr_int i ; sprintf(new_entry,"%s=%s", name, new_rhs_value) ; if (! old_rhs_value) { char **new_vector ; jr_int old_n = jr_VectorLength(old_vector) ; jr_int old_bytes = (old_n + 1) * sizeof(char *) ; jr_int new_n = old_n + 1 ; new_vector = (char **) jr_malloc((new_n + 1) * sizeof(char *)) ; memcpy(new_vector, old_vector, old_bytes) ; new_vector[new_n - 1] = new_entry ; new_vector[new_n] = 0 ; *old_entry_holder = 0 ; return(new_vector) ; } else { char *current_rhs_value ; char *current_entry ; for (i = 0 ; old_vector[i] ; i++) { current_entry = old_vector[i] ; current_rhs_value = strchr(old_vector[i], '=') ; if (current_rhs_value) { current_rhs_value++ ; /* skip over '=' */ } if (old_rhs_value == current_rhs_value) { *old_entry_holder = current_entry ; old_vector[i] = new_entry ; } } return(old_vector) ; } }
frankjas/libjr
libjr/jr_malloc/filediag.c
#include "project.h" #ifndef missing_file_descriptors #include <unistd.h> #include <fcntl.h> #endif #ifdef missing_file_descriptors void jr_MallocDiagInitExemptDescriptorArray (mdp) jr_MallocDiagStruct * mdp; { } jr_int jr_MallocDiagNumOpenFiles (mdp, wfp, error_buf) jr_MallocDiagStruct * mdp; FILE * wfp; char * error_buf; { return 0; } #else void jr_MallocDiagInitExemptDescriptorArray (mdp) jr_MallocDiagStruct * mdp; { jr_int num_fds; jr_int i; jr_int * fd_array; num_fds = sysconf (_SC_OPEN_MAX); fd_array = jr_malloc (num_fds * sizeof (jr_int)); for (i=0; i < num_fds; i++) { fd_array [i] = open ("/", O_RDONLY); if (fd_array[i] >= 0 && fd_array[i] != i) { /* * file descriptor is in use */ close (fd_array [i]); fd_array [i] = -1; } } for (i=0; i < num_fds; i++) { if (fd_array[i] == -1) { fd_array[i] = 1; } else { /* * these file descriptors weren't in use */ close (fd_array [i]); fd_array[i] = 0; } } mdp->exempt_fd_array = fd_array; } jr_int jr_MallocDiagNumOpenFiles (mdp, wfp, error_buf) jr_MallocDiagStruct * mdp; FILE * wfp; char * error_buf; { jr_int num_fds = sysconf (_SC_OPEN_MAX); jr_int num_open_files = 0; jr_int * fd_array; jr_int i; jr_int first_bad_fd = 1; char tmp_buf [32]; if (!mdp->did_initialization) { return 0; } fd_array = (jr_int *) malloc (num_fds * sizeof (jr_int)); for (i=0; i < num_fds; i++) { fd_array [i] = open ("/", O_RDONLY); if (fd_array[i] >= 0 && fd_array[i] != i) { if (! mdp->exempt_fd_array [i]) { num_open_files ++; if (wfp) { fprintf (wfp, "File descriptor %d still in use\n", i); } if (error_buf) { if (first_bad_fd) { sprintf (tmp_buf, "%d", i); error_buf [0] = 0; first_bad_fd = 0; } else { sprintf (tmp_buf, ", %d", i); } if (strlen (error_buf) + strlen (tmp_buf) < 256 - 1) { strcat (error_buf, tmp_buf); } } } close (fd_array [i]); fd_array [i] = -1; } } for (i=0; i < num_fds; i++) { if (fd_array[i] != -1) { close (fd_array [i]); } } free (fd_array); return num_open_files; } #endif
frankjas/libjr
libjr/syscalls/jr_aprglob.c
#include "ezport.h" #include <apr-1/apr_fnmatch.h> #include "jr/string.h" jr_int jr_StringHasGlobChars( const char * string) { jr_int status; status = apr_fnmatch_test( string); return status; } jr_int jr_StringHasGlobMatch( const char * string, const char * pattern, unsigned jr_int flags) { unsigned jr_int apr_flags = 0; jr_int status; if (! (flags & jr_GLOB_MATCH_PATH_SEPARATOR)) { apr_flags |= APR_FNM_PATHNAME; } if (! (flags & jr_GLOB_MATCH_PERIOD)) { apr_flags |= APR_FNM_PERIOD; } if (flags & jr_GLOB_NO_ESCAPES) { apr_flags |= APR_FNM_NOESCAPE; } if (flags & jr_GLOB_IGNORE_CASE) { apr_flags |= APR_FNM_CASE_BLIND; } status = apr_fnmatch( pattern, string, apr_flags); return status; }
frankjas/libjr
libjr/io/loglib.c
<gh_stars>0 #include "logfile.h" void jr_LogCrash (log_info) jr_LogType * log_info; { jr_file_undo( log_info->file_info); jr_file_init( log_info->file_info); } jr_int jr_LogSize( jr_LogType * log_info, jr_ULong * file_size_ref, char * error_buf) { jr_int status; jr_ULong file_size; jr_ULongAsgnUInt( &file_size, 0); status = jr_file_seek( log_info->file_info, file_size, jr_FILE_SEEK_END, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't seek: %s", error_buf); return -1; } status = jr_file_get_offset( log_info->file_info, &file_size, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't get offset: %s", error_buf); return -1; } jr_ULongAsgn( file_size_ref, file_size); return 0; } jr_int jr_LogGetOffset( jr_LogType * log_info, jr_ULong * curr_offset_ref, char * error_buf) { jr_int status; jr_ULong curr_offset; status = jr_file_get_offset( log_info->file_info, &curr_offset, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't get offset: %s", error_buf); return -1; } jr_ULongAsgn( curr_offset_ref, curr_offset); return 0; } jr_int jr_LogFlushIO( jr_LogType * log_info, char * error_buf) { jr_int status; status = jr_file_flush( log_info->file_info, error_buf); if (status != 0) { return -1; } return 0; } jr_int jr_LogGetStartTimeFromFileName( char * log_file_name, jr_ULong * start_time_ref, char * error_buf) { jr_LogEntryType entry_info[1]; jr_file_t file_info[1]; jr_int status; jr_file_init( file_info); status = jr_file_open( file_info, log_file_name, jr_FILE_OPEN_READ, 0, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't file for reading: %s", error_buf); goto return_status; } status = jr_LogEntryInitFromFilePtr ( entry_info, file_info, jr_LogHeaderEntryLength (), error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't read log header: %s", error_buf); goto return_status; } jr_LogEntryGetTime (entry_info, start_time_ref); jr_LogEntryUndo (entry_info); status = 0; return_status : { jr_file_undo( file_info); } return status; } jr_int jr_LogSetFileSyncBit (log_info, synced_bit, opt_error_buf) jr_LogType * log_info; jr_int synced_bit; char * opt_error_buf; { jr_LogEntryType entry_info[1]; jr_LogHeaderStruct * log_header; jr_ULong old_offset; jr_ULong tmp_ulong; jr_int status; if (jr_LogOpenedReadOnly (log_info)) { jr_esprintf (opt_error_buf, "not opened for writing"); return -1; } status = jr_file_get_offset( log_info->file_info, &old_offset, opt_error_buf); if (status != 0) { jr_esprintf( opt_error_buf, "couldn't get offset: %s", opt_error_buf); return -1; } jr_ULongAsgnUInt( &tmp_ulong, 0); status = jr_file_seek( log_info->file_info, tmp_ulong, jr_FILE_SEEK_SET, opt_error_buf); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf); return -1; } status = jr_LogEntryInitFromLog (entry_info, log_info, opt_error_buf); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't read log header: %s", opt_error_buf); return -1; } log_header = (void *) jr_LogEntryPtrValue (entry_info, 0); jr_NetIntAsgnInt (&log_header->is_synced, synced_bit); jr_ULongAsgnUInt( &tmp_ulong, 0); status = jr_file_seek( log_info->file_info, tmp_ulong, jr_FILE_SEEK_SET, opt_error_buf); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf); return -1; } status = jr_LogEntryAddToFilePtr ( entry_info, log_info->file_info, log_info->block_size, opt_error_buf ); jr_LogEntryUndo (entry_info); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't write log header: %s", opt_error_buf); return -1; } log_info->is_file_synced = synced_bit; status = jr_file_seek( log_info->file_info, old_offset, jr_FILE_SEEK_SET, opt_error_buf); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf); return -1; } return 0; } jr_int jr_LogSetStartTime (log_info, start_time, opt_error_buf) jr_LogType * log_info; jr_ULong start_time; char * opt_error_buf; { jr_LogEntryType entry_info[1]; jr_ULong old_offset; jr_ULong tmp_ulong; jr_int status; if (jr_LogOpenedReadOnly (log_info)) { jr_esprintf (opt_error_buf, "not opened for writing"); return -1; } status = jr_file_get_offset( log_info->file_info, &old_offset, opt_error_buf); if (status != 0) { jr_esprintf( opt_error_buf, "couldn't get offset: %s", opt_error_buf); return -1; } jr_ULongAsgnUInt( &tmp_ulong, 0); status = jr_file_seek( log_info->file_info, tmp_ulong, jr_FILE_SEEK_SET, opt_error_buf); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf); return -1; } status = jr_LogEntryInitFromLog (entry_info, log_info, opt_error_buf); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't read log header: %s", opt_error_buf); return -1; } jr_LogEntrySetTime (entry_info, start_time); status = jr_file_seek( log_info->file_info, tmp_ulong, jr_FILE_SEEK_SET, opt_error_buf); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf); return -1; } status = jr_LogEntryAddToFilePtr ( entry_info, log_info->file_info, log_info->block_size, opt_error_buf ); jr_LogEntryUndo (entry_info); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't write log header: %s", opt_error_buf); return -1; } log_info->start_time = start_time; status = jr_file_seek( log_info->file_info, old_offset, jr_FILE_SEEK_SET, opt_error_buf); if (status != 0) { jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf); return -1; } return 0; } jr_int jr_LogGetResetOffset (log_info, start_time, reset_offset_ref, error_buf) jr_LogType * log_info; jr_ULong start_time; jr_ULong* reset_offset_ref; char * error_buf; { jr_LogEntryType entry_info[1]; jr_LogHeaderStruct log_header [1]; jr_ULong reset_offset; jr_int status; status = jr_LogPadToBlockBoundary (log_info, &reset_offset, error_buf); if (status != 0) { return -1; } jr_NetIntAsgnInt (&log_header->magic_number, jr_LOG_MAGIC_NUMBER); jr_NetIntAsgnInt (&log_header->is_synced, 0); jr_NetIntAsgnInt (&log_header->block_size, log_info->block_size); jr_LogEntryInit ( entry_info, jr_LOG_HEADER_ENTRY, 0, 1, start_time, 0 ); jr_LogEntrySetPtrValue (entry_info, 0, log_header, sizeof (log_header)); status = jr_LogEntryAddToFilePtr ( entry_info, log_info->file_info, log_info->block_size, error_buf ); jr_LogEntryUndo (entry_info); if (status != 0) { return -1; } jr_ULongAsgn( reset_offset_ref, reset_offset); return 0; } jr_int jr_LogResetFromOffset (log_info, new_start_time, reset_offset, error_buf) jr_LogType * log_info; jr_ULong new_start_time; jr_ULong reset_offset; char * error_buf; { jr_ULong curr_start_time; jr_ULong tmp_ulong; jr_int status; jr_LogGetStartTime (log_info, &curr_start_time); /* * Reset the start time first, so if it fails, the log is still usable */ status = jr_LogSetStartTime (log_info, new_start_time, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't reset start time: %s", error_buf); return jr_LOG_GENERIC_ERROR; } jr_ULongAsgnUInt( &tmp_ulong, 0); status = jr_LogDeleteRange (log_info, tmp_ulong, reset_offset, error_buf); if (status != 0) { if (status == jr_LOG_CORRUPTED_ERROR) { return status;; } /* * try to restore the start time, so that the log is still usable */ status = jr_LogSetStartTime (log_info, curr_start_time, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't reset start time: %s", error_buf); return jr_LOG_CORRUPTED_ERROR; } return jr_LOG_GENERIC_ERROR; } return 0; } jr_int jr_LogTruncate (log_info, truncate_offset, opt_error_buf) jr_LogType * log_info; jr_ULong truncate_offset; char * opt_error_buf; { jr_int status; status = jr_file_truncate( log_info->file_info, truncate_offset, opt_error_buf); if (status != 0) { return status; } status = jr_file_seek( log_info->file_info, truncate_offset, jr_FILE_SEEK_SET, opt_error_buf); if (status != 0) { jr_esprintf( opt_error_buf, "couldn't seek: %s", opt_error_buf); } return 0; }
frankjas/libjr
include/jr/paragrph.h
<filename>include/jr/paragrph.h #ifndef __JR_PARAGRPH_H__ #define __JR_PARAGRPH_H__ #include <stdio.h> #include "jr/inputbuf.h" #include "jr/alist.h" #define jr_PARAGRAPH_ENDS_WITH_EOF 0x00000000 #define jr_PARAGRAPH_ENDS_WITH_BLANK_LINE 0x00000002 #define jr_PARAGRAPH_ENDS_WITH_UNESCAPED_NEWLINE 0x00000004 #define jr_PARAGRAPH_STARTS_WITH_INDENT_LESS_THAN 0x00000008 #define jr_PARAGRAPH_STARTS_WITH_INDENT_GREATER_THAN 0x00000010 #define jr_PARAGRAPH_STARTS_WITH_REGULAR_EXPRESSION 0x00000020 #define jr_PARAGRAPH_PRESERVE_INDENTATION 0x00000040 typedef struct { jr_int number_of_unescaped_newlines ; jr_AList result_listbuf[1] ; jr_int current_line_starting_index ; char * current_line_ptr ; jr_int previous_line_starting_index ; char * previous_line_ptr ; jr_int heading_line_indentation ; jr_int current_line_indentation ; jr_int previous_line_indentation ; jr_int number_of_blank_lines ; jr_int current_line_is_blank_or_comment ; jr_int first_non_white_this_line ; jr_int comment_character ; jr_int end_indentation ; char * end_expression ; unsigned paragraph_ends_with_blank_line : 1 ; unsigned paragraph_ends_with_unescaped_newline : 1 ; unsigned paragraph_starts_with_indent_less_than : 1 ; unsigned paragraph_starts_with_indent_greater_than : 1 ; unsigned paragraph_starts_with_regular_expression : 1 ; unsigned paragraph_preserve_indentation : 1 ; } jr_ParagraphStateInfoType ; extern void jr_ParagraphStateInfoInit PROTO(( jr_ParagraphStateInfoType * paragraph_info, jr_int end_indentation, const char * end_expression, jr_int comment_character, jr_int flags )) ; extern void jr_ParagraphStateInfoUndo PROTO(( jr_ParagraphStateInfoType * paragraph_info )) ; extern char * jr_ParagraphReadNewString PROTO(( jr_ParagraphStateInfoType * paragraph_info, jr_IB_InputBuffer * input_buffer )) ; extern void jr_ParagraphStart PROTO(( jr_ParagraphStateInfoType * paragraph_info )) ; extern jr_int jr_ParagraphReadLine PROTO(( jr_ParagraphStateInfoType * paragraph_info, jr_IB_InputBuffer * input_buffer )) ; extern jr_int jr_ParagraphCurrentLineIsBlankOrComment PROTO(( jr_ParagraphStateInfoType * paragraph_info )) ; extern char * jr_ParagraphCurrentLinePtr PROTO(( jr_ParagraphStateInfoType * paragraph_info )) ; extern char * jr_ParagraphCurrentParagraphPtr PROTO(( jr_ParagraphStateInfoType * paragraph_info )) ; extern void jr_ParagraphSkipToNonBlankOrCommentLine PROTO(( jr_ParagraphStateInfoType * paragraph_info, jr_IB_InputBuffer * input_buffer )) ; #endif
frankjas/libjr
libjr/htable/project.h
<filename>libjr/htable/project.h #ifndef _htable_proj_h__ #define _htable_proj_h__ #include "ezport.h" #include <assert.h> #include <stdarg.h> #include "jr/htable.h" #include "jr/malloc.h" #include "jr/misc.h" #include "jr/prefix.h" extern void jr_HTableFreeElement PROTO ((jr_HTable *htable, jr_int entry)); extern void jr_HTableIncreaseNumBuckets PROTO ((jr_HTable *htable)); extern void jr_HTableAddToBucketList PROTO ((jr_HTable *htable, jr_int index)); extern jr_int jr_HTableAllocateNewIndex PROTO ((jr_HTable * htable)); extern void jr_HTableDeleteFromBucketList PROTO (( jr_HTable * htable, jr_int delete_index )); extern void jr_HTableAddToDeleteList PROTO (( jr_HTable * htable, jr_int delete_index )); #endif
frankjas/libjr
libjr/misc/cmpstrss.c
#include "ezport.h" #include <string.h> #include <ctype.h> #include "jr/misc.h" jr_int jr_sub_strcmp(bigstr, littlestr) const char * bigstr ; const char * littlestr ; { if (strstr(bigstr, littlestr)) { return(0) ; } else { return(-1) ; } } jr_int jr_leading_strcmp(str1, str2) const char * str1 ; const char * str2 ; { jr_int l1 = strlen(str1) ; jr_int l2 = strlen(str2) ; jr_int n = (l1 < l2) ? l1 : l2 ; return(strncmp(str1, str2, n)) ; } jr_int jr_strrwordcasecmp (void_arg_1, void_arg_2) const void * void_arg_1; const void * void_arg_2; { /* * Compares on the last word of the string, ignoring case. * * Written 3/11/2002 for Groomsmen premier list. * Not well tested. */ const char * str_1 = void_arg_1; const char * str_2 = void_arg_2; char * last_word_1; char * last_word_2; last_word_1 = strrchr (str_1, 0); for (; last_word_1 > str_1; last_word_1--) { if (isspace (*last_word_1)) { last_word_1 ++; break; } } last_word_2 = strrchr (str_2, 0); for (; last_word_2 > str_2; last_word_2--) { if (isspace (*last_word_2)) { last_word_2 ++; break; } } return strcasecmp (last_word_1, last_word_2); }
frankjas/libjr
libjr/syscalls/jr_apr.c
#include "jr_apr.h" static jr_int IsInitialized = 0; static jr_int InitCount = 0; jr_int jr_apr_is_initialized () { return IsInitialized; } jr_int jr_apr_initialize_count () { return InitCount; } #define jr_APR_MAX_NUM_FREE_BLOCKS 32 void jr_apr_initialize () { if (!IsInitialized) { apr_pool_t * tmp_pool_ptr; apr_allocator_t * tmp_allocator_ptr; jr_int status; apr_initialize (); status = apr_pool_create ((apr_pool_t **) &tmp_pool_ptr, NULL); if (status == 0) { tmp_allocator_ptr = apr_pool_allocator_get(tmp_pool_ptr); if (tmp_allocator_ptr) { /* ** 2/27/07: In debug mode, try to force intermediate freeing of memory ** This may check for bounds errors earlier. Otherwise pool memory will ** be reused without bounds checks. But this may not have the intended effect, ** since only whole blocks will be freed. Fragmentation may prevent actual ** freeing. */ if ( jr_do_trace (jr_malloc_calls) || jr_do_trace (jr_malloc_trap) || jr_do_trace (jr_malloc_bounds)) { apr_allocator_max_free_set (tmp_allocator_ptr, 1); } else { apr_allocator_max_free_set (tmp_allocator_ptr, jr_APR_MAX_NUM_FREE_BLOCKS); } } } IsInitialized = 1; InitCount++; } } void jr_apr_terminate () { if (IsInitialized) { apr_terminate (); IsInitialized = 0; } } const char *jr_apr_strerror( jr_int status, char * error_buf) { if (error_buf == 0) { return ""; } return apr_strerror( status, error_buf, jr_ERROR_LEN); } jr_int jr_ConvertAprErrno ( jr_int errno_value) { /* ** 2/9/07: Under windows, each APR error condition is associated with multiple values */ if (APR_STATUS_IS_EACCES (errno_value)) { return jr_PERMISSION_ERROR; } if (APR_STATUS_IS_ENOENT (errno_value)) { return jr_NOT_FOUND_ERROR; } if (APR_STATUS_IS_EAGAIN (errno_value)) { return jr_WOULD_BLOCK_ERROR; } if (APR_STATUS_IS_EINTR (errno_value)) { return jr_INTERRUPTED_ERROR; } if (APR_STATUS_IS_TIMEUP (errno_value)) { return jr_TIME_OUT_ERROR; } if (APR_STATUS_IS_CHILD_NOTDONE (errno_value)) { return jr_WOULD_BLOCK_ERROR; } if (APR_STATUS_IS_ECONNREFUSED (errno_value)) { return jr_NOT_FOUND_ERROR; } if (APR_STATUS_IS_ENFILE (errno_value)) { return jr_NO_ROOM_ERROR; } if (APR_STATUS_IS_EMFILE (errno_value)) { return jr_NO_ROOM_ERROR; } if (APR_STATUS_IS_ENOBUFS (errno_value)) { return jr_NO_ROOM_ERROR; } if (APR_STATUS_IS_ENOMEM (errno_value)) { return jr_NO_ROOM_ERROR; } if (APR_STATUS_IS_EPROC_UNKNOWN (errno_value)) { return jr_NOT_FOUND_ERROR; } if (APR_STATUS_IS_ENOTIMPL (errno_value)) { return jr_NOT_IMPLEMENTED_ERROR; } return jr_INTERNAL_ERROR; } unsigned jr_int jr_PermsToAprPerms ( unsigned jr_int perm_flags) { apr_fileperms_t apr_mode = 0; if (perm_flags & jr_PERM_S_OWNER) { apr_mode |= APR_FPROT_USETID; } if (perm_flags & jr_PERM_S_GROUP) { apr_mode |= APR_FPROT_GSETID; } if (perm_flags & jr_PERM_R_OWNER) { apr_mode |= APR_FPROT_UREAD; } if (perm_flags & jr_PERM_W_OWNER) { apr_mode |= APR_FPROT_UWRITE; } if (perm_flags & jr_PERM_X_OWNER) { apr_mode |= APR_FPROT_UEXECUTE; } if (perm_flags & jr_PERM_R_GROUP) { apr_mode |= APR_FPROT_GREAD; } if (perm_flags & jr_PERM_W_GROUP) { apr_mode |= APR_FPROT_GWRITE; } if (perm_flags & jr_PERM_X_GROUP) { apr_mode |= APR_FPROT_GEXECUTE; } if (perm_flags & jr_PERM_R_OTHER) { apr_mode |= APR_FPROT_WREAD; } if (perm_flags & jr_PERM_W_OTHER) { apr_mode |= APR_FPROT_WWRITE; } if (perm_flags & jr_PERM_X_OTHER) { apr_mode |= APR_FPROT_WEXECUTE; } return apr_mode; } unsigned jr_int jr_AprPermsToPerms ( unsigned jr_int apr_mode) { unsigned jr_int perm_flags = 0; if (apr_mode & APR_FPROT_USETID) { perm_flags |= jr_PERM_S_OWNER; } if (apr_mode & APR_FPROT_GSETID) { perm_flags |= jr_PERM_S_GROUP; } if (apr_mode & APR_FPROT_UREAD) { perm_flags |= jr_PERM_R_OWNER; } if (apr_mode & APR_FPROT_UWRITE) { perm_flags |= jr_PERM_W_OWNER; } if (apr_mode & APR_FPROT_UEXECUTE) { perm_flags |= jr_PERM_X_OWNER; } if (apr_mode & APR_FPROT_GREAD) { perm_flags |= jr_PERM_R_GROUP; } if (apr_mode & APR_FPROT_GWRITE) { perm_flags |= jr_PERM_W_GROUP; } if (apr_mode & APR_FPROT_GEXECUTE) { perm_flags |= jr_PERM_X_GROUP; } if (apr_mode & APR_FPROT_WREAD) { perm_flags |= jr_PERM_R_OTHER; } if (apr_mode & APR_FPROT_WWRITE) { perm_flags |= jr_PERM_W_OTHER; } if (apr_mode & APR_FPROT_WEXECUTE) { perm_flags |= jr_PERM_X_OTHER; } return perm_flags; } # ifdef ostype_winnt unsigned jr_int jr_WinNtUmask = jr_PERM_RW_GROUP | jr_PERM_RW_OTHER; unsigned jr_int jr_umask_winnt( unsigned jr_int perm_flags) { unsigned jr_int old_umask = jr_WinNtUmask; jr_WinNtUmask = perm_flags; return old_umask; } #else unsigned jr_int jr_umask_winnt( unsigned jr_int perm_flags) { /* ** 2-25-2012: noop to allow for changes to the default WinNT umask w/o affecting Unix builds, */ return perm_flags; } #endif
frankjas/libjr
libjr/syscalls/jr_getcwd.c
<reponame>frankjas/libjr #include "ezport.h" #include <stdio.h> #include <unistd.h> #include <string.h> #include <errno.h> #include "jr/syscalls.h" #include "jr/malloc.h" #include "jr/error.h" jr_int jr_getcwd ( char * path_buf, jr_int path_buf_size, char * error_buf) { jr_int status; if (getcwd (path_buf, path_buf_size) == 0) { if (errno == ERANGE) { status = jr_NO_ROOM_ERROR; jr_esprintf (error_buf, "buffer too small"); } else { status = jr_ConvertErrno (errno); jr_esprintf (error_buf, "%s", strerror (errno)); } return status; } return 0; } char *jr_getcwd_malloc ( char * error_buf) { char * path_buf = 0; jr_int path_buf_size = 64; jr_int status; do { path_buf_size *= 2; path_buf = jr_realloc (path_buf, path_buf_size); if (path_buf == 0) { jr_esprintf (error_buf, "out of memory"); return 0; } status = jr_getcwd (path_buf, path_buf_size, error_buf); } while (status == jr_NO_ROOM_ERROR); if (status != 0) { jr_free (path_buf); return 0; } return path_buf; }
frankjas/libjr
libjr/misc/hashptr.c
<filename>libjr/misc/hashptr.c #include "ezport.h" #include "jr/misc.h" jr_int jr_ptrhash (ptr) const void * ptr; { return (jr_int) (intptr_t) ptr; // 10/1/07: double cast for 64-bit case } jr_int jr_ptrcmp (ptr1, ptr2) const void *ptr1; const void *ptr2; { if (ptr1 > ptr2) { return 1; } if (ptr1 < ptr2) { return -1; } return 0; } jr_int jr_ptrptrcmp (pptr1, pptr2) const void ** pptr1; const void ** pptr2; { const void * ptr1 = *pptr1; const void * ptr2 = *pptr2; if (ptr1 > ptr2) { return 1; } if (ptr1 < ptr2) { return -1; } return 0; }
frankjas/libjr
libjr/avl_tree/avl_del.c
#include "project.h" jr_int jr_AVL_TreeDeleteElement (avl_tree, key_node) jr_AVL_Tree * avl_tree; void * key_node; { void * deleted_node; deleted_node = jr_AVL_TreeExtractElementUsingKey (avl_tree, key_node); if (deleted_node == 0) { return -1; } if (jr_AVL_TreeAllocatesElements (avl_tree)) { jr_AVL_TreeFreeElement (avl_tree, deleted_node); } return 0; } void *jr_AVL_TreeExtractElementUsingKey (avl_tree, key_node) jr_AVL_Tree * avl_tree; const void * key_node; { void * path[jr_AVL_TREE_MAX_HEIGHT]; jr_int path_length; void * curr_node; jr_int comp_val; curr_node = avl_tree->root_node; path_length = 0; while (curr_node) { path[path_length] = curr_node; path_length++; comp_val = (*avl_tree->cmpfn)(key_node, curr_node, avl_tree->cmpfn_arg) ; if (comp_val == 0) { break; } else if (comp_val < 0) { curr_node = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node); } else { curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node); } } if (curr_node == 0) { return 0; } curr_node = jr_AVL_TreeExtractPathEnd (avl_tree, path, path_length); return curr_node; } void *jr_AVL_TreeExtractPathEnd (avl_tree, path, path_length) jr_AVL_Tree * avl_tree; void * path[]; jr_int path_length; { void * deleted_node; void * deleted_parent_node; void * replacement_node; void * replacement_parent_node; void * right_child; void * left_child; jr_int deleted_node_index; jr_int go_left; jr_int go_right; if (path_length == 0) { return 0; } deleted_node = path [path_length - 1]; deleted_node_index = path_length - 1; if (path_length > 1) { deleted_parent_node = path [path_length - 2]; } else { deleted_parent_node = 0; } /* * find a replacement node, if the deleted node has children * it must be the greatest node in the left sub-tree or * the smallest node in the right sub-tree. Take from the * highest sub-tree if the deleted node has both children. */ left_child = jr_AVL_TreeLeftChildPtr (avl_tree, deleted_node); right_child = jr_AVL_TreeRightChildPtr (avl_tree, deleted_node); go_left = 0; go_right = 0; if (left_child && right_child) { /* * choose replacement from highest sub-tree */ if ( jr_AVL_TreeElementHeight (avl_tree, left_child) > jr_AVL_TreeElementHeight (avl_tree, right_child)) { go_left = 1; } else { go_right = 1; } } else if (left_child) { go_left = 1; } else if (right_child) { go_right = 1; } replacement_node = 0; replacement_parent_node = 0; if (go_left) { for ( replacement_node = left_child; replacement_node; replacement_node = jr_AVL_TreeRightChildPtr (avl_tree, replacement_node), path_length++ ) { path [path_length] = replacement_node; } replacement_node = path [path_length - 1]; } else if (go_right) { for ( replacement_node = right_child; replacement_node; replacement_node = jr_AVL_TreeLeftChildPtr (avl_tree, replacement_node), path_length ++ ) { path [path_length] = replacement_node; } replacement_node = path [path_length - 1]; } if (replacement_node) { /* * The deleted_node has descendents, replace it with the replacement node. * path containes the deleted node and replacement, so path_length - 2 is >= 0 * path [path_length - 2] contains the parent of the replacement node. */ replacement_parent_node = path [path_length - 2]; /* * delete the replacement node by changing its parent's child pointer */ if (replacement_parent_node == deleted_node) { if (go_left) { /* * just went left, replacement has no right child * take this sub-tree and add it to the right child of the replacement's parent */ jr_AVL_TreeLeftChildPtr (avl_tree, replacement_parent_node) = jr_AVL_TreeLeftChildPtr (avl_tree, replacement_node); } else if (go_right) { /* * must mean we went right, because we went until the left child was 0 * take this sub-tree and add it to the left child of the replacement's parent */ jr_AVL_TreeRightChildPtr (avl_tree, replacement_parent_node) = jr_AVL_TreeRightChildPtr (avl_tree, replacement_node); } } else if (go_left) { /* * must we went left then right as far as possible ==> replacement is right child * take this sub-tree and add it to the right child of the replacement's parent */ jr_AVL_TreeRightChildPtr (avl_tree, replacement_parent_node) = jr_AVL_TreeLeftChildPtr (avl_tree, replacement_node); } else if (go_right) { /* * must we went right then left as far as possible ==> replacement is left child * must mean we went right, because we went until the left child was 0 * take this sub-tree and add it to the left child of the replacement's parent */ jr_AVL_TreeLeftChildPtr (avl_tree, replacement_parent_node) = jr_AVL_TreeRightChildPtr (avl_tree, replacement_node); } /* * now the replacement node is ready to be switched with the deleted node */ jr_AVL_TreeLeftChildPtr (avl_tree, replacement_node) = jr_AVL_TreeLeftChildPtr (avl_tree, deleted_node); jr_AVL_TreeRightChildPtr (avl_tree, replacement_node) = jr_AVL_TreeRightChildPtr (avl_tree, deleted_node); jr_AVL_TreeElementHeight (avl_tree, replacement_node) = jr_AVL_TreeElementHeight (avl_tree, deleted_node); if (jr_AVL_TreeMaintainsSize (avl_tree)) { jr_AVL_TreeSetSubTreeSize ( avl_tree, replacement_node, jr_AVL_TreeSubTreeSize (avl_tree, deleted_node) ); } } if (deleted_parent_node) { /* * has parent, replacement node is either 0, or the correct replacement */ if (jr_AVL_TreeLeftChildPtr (avl_tree, deleted_parent_node) == deleted_node) { jr_AVL_TreeLeftChildPtr (avl_tree, deleted_parent_node) = (void *) replacement_node; } if (jr_AVL_TreeRightChildPtr (avl_tree, deleted_parent_node) == deleted_node) { jr_AVL_TreeRightChildPtr (avl_tree, deleted_parent_node) = (void *) replacement_node; } } else { avl_tree->root_node = replacement_node; } path [deleted_node_index] = replacement_node; /* * if there was a replacement, the path goes to the replacement node. * with no replacement, it goes to the deleted_node * * If there was a replacement, we want to start balancing * with the parent of the replacement node (path_length - 1 is the path length). * If the deleted node was the parent of the replacement * we want to start balancing with the deleted node (deleted_node_index + 1 * is the path length, but in this case that equals path_length - 1). * * If there was no replacement node, then we want to start balancing * with the parent of the deleted node. */ if (jr_AVL_TreeMaintainsSize (avl_tree)) { jr_int i; for (i=0; i < path_length - 1; i++) { jr_AVL_TreeDecrementElementTreeSize (avl_tree, path[i]); } } jr_AVL_TreeBalancePath (avl_tree, path, path_length - 1); jr_AVL_TreeMakeNullElement (avl_tree, deleted_node); /* * so prefix transformations on this element don't affect anything */ return (void *) deleted_node; } void jr_AVL_TreeMakeNullElement (avl_tree, el_ptr) jr_AVL_Tree * avl_tree; void * el_ptr; { jr_AVL_TreeLeftChildPtr (avl_tree, el_ptr) = 0; jr_AVL_TreeRightChildPtr (avl_tree, el_ptr) = 0; jr_AVL_TreeElementHeight (avl_tree, el_ptr) = -1; }
frankjas/libjr
libjr/ansi_c/c_expr_node.c
<reponame>frankjas/libjr #include "ezport.h" #include <string.h> #include "jr/malloc.h" #include "jr/misc.h" #include "jr/ansi_c/exprnode.h" jr_C_ExprNodeType * jr_C_ExprNodeCreate (node_type, child0, child1, child2) jr_int node_type; jr_C_ExprNodeType * child0; jr_C_ExprNodeType * child1; jr_C_ExprNodeType * child2; { jr_C_ExprNodeType * c_expr_node; c_expr_node = jr_malloc (sizeof (*c_expr_node)); memset (c_expr_node, 0, sizeof (*c_expr_node)); c_expr_node->node_type = node_type; c_expr_node->children[0] = child0; c_expr_node->children[1] = child1; c_expr_node->children[2] = child2; jr_C_ExprNodeSetVoidValue (c_expr_node); return (c_expr_node); } void jr_C_ExprNodeDestroy (c_expr_node) jr_C_ExprNodeType * c_expr_node; { jr_C_ExprNodeTraverse (c_expr_node, 0, 0, jr_C_ExprNodeTraversalDestroy, 0, 0); /* * post order free, no error can be generated */ } jr_C_ExprNodeType * jr_C_ExprNodeListCreate (node_type, child0, child1, child2) jr_int node_type; jr_C_ExprNodeType * child0; jr_C_ExprNodeType * child1; jr_C_ExprNodeType * child2; { jr_C_ExprNodeType * new_list_node; jr_C_ExprNodeType * c_expr_node; c_expr_node = jr_C_ExprNodeCreate( node_type, child0, child1, child2); new_list_node = jr_C_ExprNodeListCreateWithNode( c_expr_node); return new_list_node; } jr_C_ExprNodeType * jr_C_ExprNodeListCreateWithNode (c_expr_node) jr_C_ExprNodeType * c_expr_node; { jr_C_ExprNodeType * new_list_node; new_list_node = jr_C_ExprNodeCreate( jr_C_EXPR_NODE_LIST_TYPE, c_expr_node, 0, 0); return new_list_node; } void jr_C_ExprNodeListAppendNew (list_node, node_type, child0, child1, child2) jr_C_ExprNodeType * list_node; jr_int node_type; jr_C_ExprNodeType * child0; jr_C_ExprNodeType * child1; jr_C_ExprNodeType * child2; { jr_C_ExprNodeType * new_node; new_node = jr_C_ExprNodeCreate( node_type, child0, child1, child2); jr_C_ExprNodeListAppendNode (list_node, new_node); } void jr_C_ExprNodeListAppendNode (list_node, new_node) jr_C_ExprNodeType * list_node; jr_C_ExprNodeType * new_node; { jr_C_ExprNodeType * new_list_node; if (list_node->node_type != jr_C_EXPR_NODE_LIST_TYPE) { jr_coredump(); } new_list_node = jr_C_ExprNodeListCreateWithNode (new_node); while (jr_C_ExprNodeRightChildPtr (list_node) != 0) { list_node = jr_C_ExprNodeRightChildPtr (list_node); } jr_C_ExprNodeSetRightChild(list_node, new_list_node); } void jr_C_ExprNodeListAppendList (list_node, append_list_node) jr_C_ExprNodeType * list_node; jr_C_ExprNodeType * append_list_node; { if (list_node->node_type != jr_C_EXPR_NODE_LIST_TYPE) { jr_coredump(); } while (jr_C_ExprNodeRightChildPtr (list_node) != 0) { list_node = jr_C_ExprNodeRightChildPtr (list_node); } jr_C_ExprNodeSetRightChild(list_node, append_list_node); } jr_int jr_C_ExprNodeTraversalDestroy (c_expr_node) jr_C_ExprNodeType * c_expr_node; { /* * needs to take an expression first since it is * a traversal function */ if (jr_C_ExprNodeAllocFn( c_expr_node)) { jr_C_ExprNodeCallAllocFn( c_expr_node, jr_C_EXPR_VOID_VALUE, c_expr_node, 0); } jr_free (c_expr_node); return (0); /* * return good status so we can use this as a traversal function */ } jr_int jr_C_ExprNodeTraverse ( curr_node, pre_order_fn, in_order_fn, post_order_fn, data_ptr, opt_error_buf ) jr_C_ExprNodeType * curr_node; jr_int (*pre_order_fn) (); jr_int (*in_order_fn) (); jr_int (*post_order_fn) (); void * data_ptr; char * opt_error_buf; { jr_C_ExprNodeType * left_node; jr_C_ExprNodeType * right_node; jr_C_ExprNodeType * extra_node; jr_int status = 0; if (curr_node->node_type != jr_C_EXPR_NODE_LIST_TYPE) { left_node = jr_C_ExprNodeLeftChildPtr (curr_node); right_node = jr_C_ExprNodeRightChildPtr (curr_node); extra_node = jr_C_ExprNodeExtraChildPtr (curr_node); if (pre_order_fn) { status = (*pre_order_fn) (curr_node, data_ptr, opt_error_buf); if (status != 0) { return (status); } } if (left_node) { status = jr_C_ExprNodeTraverse ( left_node, pre_order_fn, in_order_fn, post_order_fn, data_ptr, opt_error_buf ); if (status != 0) { return (status); } } if (in_order_fn) { status = (*in_order_fn) (curr_node, data_ptr, opt_error_buf); if (status != 0) { return (status); } } if (right_node) { status = jr_C_ExprNodeTraverse ( right_node, pre_order_fn, in_order_fn, post_order_fn, data_ptr, opt_error_buf ); if (status != 0) { return (status); } } if (extra_node) { status = jr_C_ExprNodeTraverse ( extra_node, pre_order_fn, in_order_fn, post_order_fn, data_ptr, opt_error_buf ); if (status != 0) { return (status); } } if (post_order_fn) { status = (*post_order_fn) (curr_node, data_ptr, opt_error_buf); if (status != 0) { return (status); } } } else { /* * its a list token, and shouldn't be visited * the left node is the expression, and the right node * is the pointer to the next list element */ for (; curr_node != 0; curr_node = right_node) { left_node = jr_C_ExprNodeLeftChildPtr (curr_node); right_node = jr_C_ExprNodeRightChildPtr (curr_node); if (left_node) { status = jr_C_ExprNodeTraverse ( left_node, pre_order_fn, in_order_fn, post_order_fn, data_ptr, opt_error_buf ); if (status != 0) { return (status); } } if (post_order_fn == jr_C_ExprNodeTraversalDestroy) { jr_C_ExprNodeTraversalDestroy (curr_node); } } } return (status); } void jr_C_ExprNodeInitCopy (new_node, c_expr_node) jr_C_ExprNodeType * new_node; jr_C_ExprNodeType * c_expr_node; { jr_C_ExprNodeType * left_node; jr_C_ExprNodeType * right_node; jr_C_ExprNodeType * extra_node; void (*node_alloc_fn)( jr_int op_type, jr_C_ExprNodeType * new_node, jr_C_ExprNodeType * c_expr_node ) = 0; memcpy (new_node, c_expr_node, sizeof (*new_node)); left_node = jr_C_ExprNodeLeftChildPtr (c_expr_node); right_node = jr_C_ExprNodeRightChildPtr (c_expr_node); extra_node = jr_C_ExprNodeExtraChildPtr (c_expr_node); if (left_node) { jr_C_ExprNodeLeftChildPtr (new_node) = jr_C_ExprNodeCreateCopy (left_node); node_alloc_fn = jr_C_ExprNodeAllocFn( left_node); } if (right_node) { jr_C_ExprNodeRightChildPtr (new_node) = jr_C_ExprNodeCreateCopy (right_node); node_alloc_fn = jr_C_ExprNodeAllocFn( right_node); } if (extra_node) { jr_C_ExprNodeExtraChildPtr (new_node) = jr_C_ExprNodeCreateCopy (extra_node); node_alloc_fn = jr_C_ExprNodeAllocFn( extra_node); } if (node_alloc_fn) { node_alloc_fn( jr_C_EXPR_PTR_VALUE, new_node, c_expr_node); } } jr_C_ExprNodeType *jr_C_ExprNodeCreateCopy (c_expr_node) jr_C_ExprNodeType * c_expr_node; { jr_C_ExprNodeType * new_node; new_node = jr_malloc (sizeof (*new_node)); jr_C_ExprNodeInitCopy (new_node, c_expr_node); return new_node; }
frankjas/libjr
include/jr/misc.h
<reponame>frankjas/libjr #ifndef _jr_misc_h__ #define _jr_misc_h__ #include "ezport.h" #include <stdio.h> #define jr_INT_NULL jr_INT_MIN #define jr_SHRT_NULL jr_SHRT_MIN #define jr_PI (3.14159265358979323846L) #define jr_abs(x) (x < 0 ? -x : x) #define jr_max(x,y) ((x)>(y)?(x):(y)) #define jr_min(x,y) ((x)<(y)?(x):(y)) #define jr_array_num_elements(array_name) \ (sizeof (array_name) / sizeof (array_name[0])) #define jr_word_align_up(s) \ ((s) & jr_INT_NUM_BYTES_MASK \ ? ((s) + jr_INT_NUM_BYTES) & ~jr_INT_NUM_BYTES_MASK \ : (s) \ ) #define jr_word_align_down(s) \ (((jr_int)(s)) & ~jr_INT_NUM_BYTES_MASK) extern unsigned jr_int jr_next2power PROTO ((jr_int number)); extern jr_int jr_is2power PROTO ((jr_int number)); extern unsigned jr_int jr_get2power PROTO ((jr_int power)); extern jr_int jr_log_of_2_power PROTO ((jr_int number)); #define jr_HasFlag(var,mask) ((var) & (mask)) #define jr_SetFlag(var,mask) ((var) |= (mask)) #define jr_UnSetFlag(var,mask) ((var) &= ~(mask)) #define jr_UIntMaskedValue(l, mask) ((l) & (mask)) #define jr_UIntMaskedAsgn(lp, mask, v) (*(lp) = (*(lp) & ~(mask)) | ((v) & (mask))) /******** Compare And Hash Functions ********/ typedef jr_int (*jr_CmpFnType) PROTO ((const void *, const void *)); typedef jr_int (*jr_HashFnType) PROTO ((const void *)); extern jr_int jr_rev_strcmp PROTO ((const char *s1, const char *s2)); extern jr_int jr_leading_strcmp PROTO ((const char *s1, const char * s2)); extern jr_int jr_sub_strcmp PROTO ((const char *big_str, const char *small_str)); extern jr_int jr_strrwordcasecmp PROTO ((const void *void_arg_1, const void *void_arg_2)); /* * Compares on the last word of the string, ignoring case. */ extern jr_int jr_strpcmp PROTO ((const void *, const void *)) ; extern jr_int jr_stricmp PROTO ((const void *, const void *)) ; extern jr_int jr_trailing_filename_pcmp PROTO ((const char **, const char **)) ; extern jr_int jr_opt_strcmp PROTO ((const char *, const char *)); extern jr_int jr_opt_strcasecmp PROTO ((const char *, const char *)); extern jr_int jr_canon_strcmp PROTO ((const char *, const char *)); extern jr_int jr_opt_canon_strcmp PROTO ((const char *, const char *)); extern jr_int jr_canon_is_prefix PROTO ((const char *, const char *)); extern jr_int jr_ptrcmp PROTO ((const void *, const void *)) ; extern jr_int jr_ptrhash PROTO ((const void *)); extern jr_int jr_ptrptrcmp PROTO ((const void **, const void **)) ; extern jr_int jr_intcmp PROTO ((jr_int, jr_int)) ; extern jr_int jr_inthash PROTO ((jr_int)); extern jr_int jr_rintcmp PROTO ((jr_int, jr_int)) ; extern jr_int jr_rintpcmp PROTO ((const jr_int *, const jr_int *)) ; extern jr_int jr_intpcmp PROTO ((const void *, const void *)) ; extern jr_int jr_intphash PROTO ((const void *)); extern jr_int jr_intstrcmp PROTO ((const jr_int *, const jr_int *)); extern jr_int jr_intstrhash PROTO ((const jr_int *)); extern jr_int jr_intstrlen PROTO ((const jr_int *)); extern jr_int jr_intstrbytes PROTO ((const jr_int *)); extern jr_int jr_intstrlenhash PROTO ((const jr_int *, jr_int)); extern jr_int jr_shortstrcmp PROTO ((const short *, const short *)); extern jr_int jr_shortstrhash PROTO ((const short *)); extern jr_int jr_shortstrbytes PROTO ((const short *)); extern jr_int jr_shortstrlenhash PROTO ((const short *, jr_int)); extern jr_int jr_ushort_add_max ( unsigned jr_short * ushort_ref, jr_int addend); extern jr_int jr_posintcmp PROTO ((jr_int, jr_int)) ; /* * non-zero integers compared, zero > all */ extern jr_int jr_posintpcmp PROTO ((const jr_int *, const jr_int *)) ; /* * non-zero integers compared, zero > all */ extern jr_int jr_always_true_cmp () ; extern jr_int jr_always_false_cmp () ; extern jr_int jr_strhash PROTO ((const void *)) ; extern jr_int jr_strhash_pjw PROTO ((const void *)); extern jr_int jr_strcasehash_pjw PROTO ((const void *)); extern jr_int jr_strlenhash PROTO ((const void *, jr_int)); /******** Other Functions ********/ extern void jr_coredump PROTO ((void)); extern void jr_debugger_trap PROTO ((void)); extern char * jr_MakeDiagFileName PROTO (( char * diag_file_buf, jr_int diag_file_buf_size, const char * file_name )); extern char jr_DiagFileDirectory[256]; #define jr_SetDiagFileDirectory(dir_path) \ strncpy (jr_DiagFileDirectory, dir_path, sizeof (jr_DiagFileDirectory) - 1) /* * Has a null, since globals start out all zero */ #define jr_HasDiagFileDirectory() \ (jr_DiagFileDirectory[0]) #define jr_GetDiagFileDirectory() \ (jr_DiagFileDirectory) extern void jr_freeref PROTO ((char **ptr_to_be_derefd_and_freed)) ; extern void jr_memswitch PROTO ((void *p1, void *p2, jr_int nbytes)); extern jr_int jr_memisset PROTO ((void *p1, jr_int value, jr_int nbytes)); extern void jr_memscoot PROTO (( void * buffer, jr_int buffer_size, jr_int hole_offset, jr_int hole_size )); extern void * jr_BinarySearchInsertPtr PROTO(( const void * base, jr_int num_items, jr_int sizeof_each_item, jr_int (*compf)(), const void * search_key )) ; extern void * jr_BinarySearch PROTO(( const void * base, jr_int num_items, jr_int sizeof_each_item, jr_int (*compf)(), const void * key_or_pattern )) ; extern void * jr_LinearSearch PROTO(( const void * base, jr_int num_items, jr_int sizeof_each_item, jr_int (*compf)(), const void * key_or_pattern )) ; extern double jr_StringExpressionToDouble PROTO(( const char * string )) ; extern unsigned long jr_CRC_seeded_chksum PROTO(( unsigned char * p, jr_int len, short seed )) ; extern unsigned long jr_CRC_chksum PROTO(( void * byte_string_arg, jr_int length )) ; extern jr_int jr_EnvTabStops PROTO ((void)); extern void * jr_heap_base(void); extern jr_int jr_backtrace PROTO (( void ** pc_array, jr_int pc_array_size )); extern jr_int jr_random_bytes ( void * bytes_ptr, jr_int bytes_length, char * opt_error_buf); extern jr_int jr_base64_encode ( char * encoded_dest, const char * plain_src, jr_int plain_src_length); extern jr_int jr_base64_encode_binary ( char * encoded_dest, const unsigned char * plain_src, jr_int plain_src_length); /******** PostScript ********/ extern jr_int jr_PostScriptLineGetPageNumber PROTO (( char * lbuf )); extern char * jr_PostScriptLineGetShowText PROTO (( char * lbuf, char * text )); typedef struct { float lower_left_x ; float lower_left_y ; float upper_right_x ; float upper_right_y ; float range_x ; float range_y ; } jr_PS_BoundingBoxStruct ; typedef struct { float trans_x ; float trans_y ; float scale_x ; float scale_y ; float rotation ; jr_int justify ; float vert_space ; float page_width; float margin_width; } jr_PS_TransformStruct ; extern jr_int jr_PostScriptFileGetBoundingBox PROTO (( FILE * rfp, jr_PS_BoundingBoxStruct * box_ptr )); extern void jr_PostScriptPrintTransform PROTO (( jr_PS_TransformStruct * trans_info, jr_PS_BoundingBoxStruct * box_ptr, FILE * wfp, char * roff_ps_prefix )); extern void jr_PS_TransformInit PROTO (( jr_PS_TransformStruct * trans_info, float trans_x, float trans_y, float scale_x, float scale_y, float rotation, jr_int justify, float vert_space, float page_width, float margin_width )); #endif
frankjas/libjr
libjr/syscalls/jr_process.c
<reponame>frankjas/libjr<filename>libjr/syscalls/jr_process.c<gh_stars>0 #include "ezport.h" #include <string.h> #include <signal.h> #include <apr-1/apr_pools.h> #include <apr-1/apr_thread_proc.h> #include <apr-1/apr_lib.h> #include "jr/apr.h" #include "jr/error.h" #include "jr/malloc.h" void jr_process_init ( jr_process_t * process_ptr) { memset (process_ptr, 0, sizeof (*process_ptr)); process_ptr->apr_proc_ptr = jr_malloc (sizeof (apr_proc_t)); memset( process_ptr->apr_proc_ptr, 0, sizeof( apr_proc_t)); jr_file_init (process_ptr->input_wfi); jr_file_init (process_ptr->output_rfi); jr_file_init (process_ptr->error_rfi); } void jr_process_undo ( jr_process_t * process_ptr) { if (process_ptr->apr_proc_ptr && process_ptr->apr_pool_ptr) { apr_pool_note_subprocess ( process_ptr->apr_pool_ptr, process_ptr->apr_proc_ptr, APR_KILL_AFTER_TIMEOUT ); /* ** 2/22/07: first send SIGTERM, wait() 3 seconds, then send SIGKILL, then wait() */ } if (process_ptr->apr_pool_ptr) { apr_pool_destroy (process_ptr->apr_pool_ptr); } jr_free (process_ptr->apr_proc_ptr); jr_file_undo (process_ptr->input_wfi); jr_file_undo (process_ptr->output_rfi); jr_file_undo (process_ptr->error_rfi); } void jr_procattr_child_errfn ( apr_pool_t * apr_pool_ptr, jr_int errno, const char * error_str) { fprintf (stderr, "%s\n", error_str); } jr_int jr_process_init_procattr ( jr_process_t * process_ptr, char * error_buf) { jr_int status; if (process_ptr->apr_procattr_ptr) { return 0; } if (process_ptr->apr_pool_ptr == 0) { status = apr_pool_create ((apr_pool_t **) &process_ptr->apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } status = apr_procattr_create ( (apr_procattr_t **) &process_ptr->apr_procattr_ptr, process_ptr->apr_pool_ptr ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } apr_procattr_cmdtype_set (process_ptr->apr_procattr_ptr, APR_PROGRAM_PATH); /* ** 2/22/07: do a path search by default, use parents env. */ apr_procattr_io_set (process_ptr->apr_procattr_ptr, APR_NO_PIPE, APR_NO_PIPE, APR_NO_PIPE); /* ** 2/22/07: no pipes back to the parent */ apr_procattr_child_errfn_set ( process_ptr->apr_procattr_ptr, (apr_child_errfn_t *) jr_procattr_child_errfn ); # ifdef ostype_winnt { if (0) { apr_procattr_detach_set (process_ptr->apr_procattr_ptr, TRUE); /* ** 2/22/07: No command window under microsoft (no control terminal under Linux) ** 2/23/07: Detaching under windows causes spawning problems when running from the ** command line. */ } } # endif status = 0; return_status : { } return status; } jr_int jr_process_set_input ( jr_process_t * process_ptr, jr_file_t * child_rfi, jr_file_t * opt_parent_pipe_wfi, char * error_buf) { jr_int status; if (process_ptr->apr_procattr_ptr == 0) { status = jr_process_init_procattr (process_ptr, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't create process attributes: %s", error_buf); goto return_status; } } status = apr_procattr_child_in_set ( process_ptr->apr_procattr_ptr, jr_file_apr_ptr (child_rfi), opt_parent_pipe_wfi ? jr_file_apr_ptr (opt_parent_pipe_wfi) : 0 ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_process_set_output ( jr_process_t * process_ptr, jr_file_t * child_wfi, jr_file_t * opt_parent_pipe_rfi, char * error_buf) { jr_int status; if (process_ptr->apr_procattr_ptr == 0) { status = jr_process_init_procattr (process_ptr, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't create process attributes: %s", error_buf); goto return_status; } } status = apr_procattr_child_out_set ( process_ptr->apr_procattr_ptr, jr_file_apr_ptr (child_wfi), opt_parent_pipe_rfi ? jr_file_apr_ptr (opt_parent_pipe_rfi) : 0 ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_process_set_error ( jr_process_t * process_ptr, jr_file_t * child_wfi, jr_file_t * opt_parent_pipe_rfi, char * error_buf) { jr_int status; if (process_ptr->apr_procattr_ptr == 0) { status = jr_process_init_procattr (process_ptr, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't create process attributes: %s", error_buf); goto return_status; } } status = apr_procattr_child_err_set ( process_ptr->apr_procattr_ptr, jr_file_apr_ptr (child_wfi), opt_parent_pipe_rfi ? jr_file_apr_ptr (opt_parent_pipe_rfi) : 0 ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_process_make_pipes ( jr_process_t * process_ptr, jr_int input_kind, jr_int output_kind, jr_int error_kind, char * error_buf) { jr_int apr_input_kind; jr_int apr_output_kind; jr_int apr_error_kind; jr_int status; if (process_ptr->apr_procattr_ptr == 0) { status = jr_process_init_procattr (process_ptr, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't create process attributes: %s", error_buf); goto return_status; } } if (input_kind == jr_PROCESS_NO_PIPE) { apr_input_kind = APR_NO_PIPE; } else if (input_kind == jr_PROCESS_NONBLOCKING_PIPE) { apr_input_kind = APR_CHILD_BLOCK; } else { apr_input_kind = APR_FULL_BLOCK; } if (output_kind == jr_PROCESS_NO_PIPE) { apr_output_kind = APR_NO_PIPE; } else if (output_kind == jr_PROCESS_NONBLOCKING_PIPE) { apr_output_kind = APR_CHILD_BLOCK; } else { apr_output_kind = APR_FULL_BLOCK; } if (error_kind == jr_PROCESS_NO_PIPE) { apr_error_kind = APR_NO_PIPE; } else if (error_kind == jr_PROCESS_NONBLOCKING_PIPE) { apr_error_kind = APR_FULL_NONBLOCK; } else { apr_error_kind = APR_FULL_BLOCK; } status = apr_procattr_io_set( process_ptr->apr_procattr_ptr, apr_input_kind, apr_output_kind, apr_error_kind ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_process_spawn ( jr_process_t * process_ptr, const char * prog_name, const char ** opt_argv, const char ** opt_envp, char * error_buf) { const char *const* argv = opt_argv; const char * default_argv[2]; jr_int status; default_argv[0] = prog_name; default_argv[1] = 0; if (argv == 0) { argv = default_argv; } if (process_ptr->apr_procattr_ptr == 0) { status = jr_process_init_procattr (process_ptr, error_buf); if (status != 0) { jr_esprintf (error_buf, "couldn't create process attributes: %s", error_buf); goto return_status; } } if (opt_envp == 0) { } status = apr_proc_create ( process_ptr->apr_proc_ptr, prog_name, argv, opt_envp, process_ptr->apr_procattr_ptr, process_ptr->apr_pool_ptr ); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } if (((apr_proc_t *) process_ptr->apr_proc_ptr)->in) { jr_file_set_apr_ptr (process_ptr->input_wfi, ((apr_proc_t *)process_ptr->apr_proc_ptr)->in); } if (((apr_proc_t *) process_ptr->apr_proc_ptr)->out) { jr_file_set_apr_ptr (process_ptr->output_rfi, ((apr_proc_t *)process_ptr->apr_proc_ptr)->out); } if (((apr_proc_t *) process_ptr->apr_proc_ptr)->err) { jr_file_set_apr_ptr (process_ptr->error_rfi, ((apr_proc_t *)process_ptr->apr_proc_ptr)->err); } status = 0; return_status : { } return status; } jr_int jr_process_wait ( jr_process_t * process_ptr, jr_int flags, jr_int * exit_status_ref, jr_int * exit_why_ref, char * error_buf) { jr_int exit_status; apr_exit_why_e exit_why; apr_wait_how_e wait_how; jr_int status; if (flags & jr_PROCESS_WAIT_NON_BLOCK) { wait_how = APR_NOWAIT; } else { wait_how = APR_WAIT; } status = apr_proc_wait ( process_ptr->apr_proc_ptr, &exit_status, &exit_why, wait_how ); if (APR_STATUS_IS_CHILD_DONE (status)) { status = 0; } else if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } *exit_status_ref = exit_status; *exit_why_ref = 0; if (exit_why & APR_PROC_EXIT) { *exit_why_ref |= jr_PROCESS_EXITTED; } if (exit_why & APR_PROC_SIGNAL) { *exit_why_ref |= jr_PROCESS_WAS_SIGNALLED; } if (exit_why & APR_PROC_SIGNAL_CORE) { *exit_why_ref |= jr_PROCESS_HAS_CORE; } status = 0; return_status : { } return status; } jr_int jr_process_kill ( jr_process_t * process_ptr, jr_int signum_status, char * error_buf) { jr_int status; /* ** 11-29-2011: in MS the signal is used as the exit status ** argument for TerminateProcess() */ if (signum_status < 0) { # ifdef ostype_winnt signum_status = 1; # else signum_status = SIGKILL; # endif } status = apr_proc_kill ( process_ptr->apr_proc_ptr, signum_status); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { } return status; } jr_int jr_process_id ( jr_process_t * process_ptr) { return ((apr_proc_t *) process_ptr->apr_proc_ptr)->pid; }
frankjas/libjr
libjr/syscalls/jr_password.c
#include "ezport.h" #include <apr-1/apr_md5.h> #include <apr-1/apr_sha1.h> #include "jr/error.h" jr_int jr_password_check( const char * password_str, const char * hashed_str) { apr_status_t status; status = apr_password_validate( password_str, hashed_str); if (status == 0) { return 0; } return jr_PERMISSION_ERROR; } void jr_password_hash( const char * password_str, const char * salt_str, char * hash_buf, jr_int hash_buf_len) { apr_md5_encode( password_str, salt_str, hash_buf, hash_buf_len); }
frankjas/libjr
libjr/io/bufio.c
#include "ezport.h" #include <errno.h> #include "jr/bufio.h" #include "jr/error.h" #include "jr/string.h" #include "jr/malloc.h" void jr_BufferedIoInit ( jr_BufferedIoType * buf_io) { memset (buf_io, 0, sizeof (*buf_io)); jr_AListInit (buf_io->data_buffer, sizeof (char)); } void jr_BufferedIoUndo ( jr_BufferedIoType * buf_io) { jr_AListUndo (buf_io->data_buffer); if (buf_io->read_buffer) { jr_free( buf_io->read_buffer); } } void jr_BufferedIoSetRawReadFn( jr_BufferedIoType * buf_io, jr_BufferedIoRawReadFn * raw_read_fn, void * raw_read_arg) { buf_io->raw_read_fn = raw_read_fn; buf_io->raw_read_arg = raw_read_arg; } jr_int jr_BufferedIoGetLine ( jr_BufferedIoType * buf_io, char ** line_buffer_ref, char * error_buf) { char * line_buffer; jr_int line_length; const char * newline_ptr = 0; jr_int q; jr_int status; /* ** 12/27/06: data from the last read may still be referenced by buf_io->data_ptr */ if (jr_AListSize (buf_io->data_buffer) > 0) { jr_esprintf (error_buf, "internal buffer still has data"); status = jr_MISUSE_ERROR; goto return_status; } while (1) { if (buf_io->data_length == 0) { status = buf_io->raw_read_fn ( buf_io->raw_read_arg, 0, &buf_io->data_ptr, &buf_io->data_length, error_buf ); if (status != 0) { goto return_status; } if (buf_io->data_length == 0) { if (jr_AListSize (buf_io->data_buffer) == 0) { jr_esprintf (error_buf, "end of input"); status = jr_EOF_ERROR; goto return_status; } jr_AListNativeSetNewTail (buf_io->data_buffer, 0, char); line_length = jr_AListSize (buf_io->data_buffer) - 1; line_buffer = jr_AListExtractBuffer (buf_io->data_buffer); break; } } /* ** 12/27/06: look for the newline, note: data_ptr is not a string */ newline_ptr = jr_strnchr (buf_io->data_ptr, '\n', buf_io->data_length); if (newline_ptr) { line_length = newline_ptr - buf_io->data_ptr; if (newline_ptr[-1] == '\r') { line_length --; } if (jr_AListSize (buf_io->data_buffer) > 0) { /* ** 12/27/06: We've already buffered some of the data, add the rest to the buffer */ for (q=0; q < line_length; q++) { jr_AListNativeSetNewTail (buf_io->data_buffer, buf_io->data_ptr[q], char); } jr_AListNativeSetNewTail (buf_io->data_buffer, 0, char); line_length = jr_AListSize (buf_io->data_buffer) - 1; line_buffer = jr_AListExtractBuffer (buf_io->data_buffer); } else { line_buffer = jr_malloc (line_length + 1); memcpy (line_buffer, buf_io->data_ptr, line_length); line_buffer[line_length] = 0; } buf_io->data_length -= newline_ptr + 1 - buf_io->data_ptr; buf_io->data_ptr = newline_ptr + 1; break; } else { /* ** 12/27/06: No newline, add the current data to our buffer */ for (q=0; q < (jr_int) buf_io->data_length; q++) { jr_AListNativeSetNewTail (buf_io->data_buffer, buf_io->data_ptr[q], char); } buf_io->data_length = 0; } } status = line_length; *line_buffer_ref = line_buffer; return_status : { } return status; } jr_int jr_BufferedIoGetString ( jr_BufferedIoType * buf_io, unsigned jr_int desired_string_length, char ** string_ref, char * error_buf) { char * string; jr_int leftover_length; jr_int q; jr_int status; /* ** 12/27/06: data from the last read may still be referenced by buf_io->data_ptr */ while (1) { /* ** 9/16/07: The following cases only occur if GetKnownData() call can't read enough data ** then is called again? */ if ((unsigned jr_int) jr_AListSize (buf_io->data_buffer) == desired_string_length) { jr_AListNativeSetNewTail (buf_io->data_buffer, 0, char); string = jr_AListExtractBuffer (buf_io->data_buffer); } else if ((unsigned jr_int) jr_AListSize (buf_io->data_buffer) > desired_string_length) { jr_int original_size; original_size = jr_AListSize (buf_io->data_buffer); string = jr_AListExtractBuffer (buf_io->data_buffer); for (q=desired_string_length; q < original_size; q++) { jr_AListNativeSetNewTail (buf_io->data_buffer, string[q], char); } string[desired_string_length] = 0; break; } if (buf_io->data_length == 0) { status = buf_io->raw_read_fn( buf_io->raw_read_arg, 0, &buf_io->data_ptr, &buf_io->data_length, error_buf ); if (status != 0) { goto return_status; } if (buf_io->data_length == 0) { if (jr_AListSize (buf_io->data_buffer) > 0) { jr_esprintf (error_buf, "only found %d of %d bytes", jr_AListSize (buf_io->data_buffer), desired_string_length ); status = jr_MISUSE_ERROR; } else { jr_esprintf (error_buf, "end of input"); status = jr_EOF_ERROR; } goto return_status; } } if (jr_AListSize (buf_io->data_buffer) + buf_io->data_length < desired_string_length) { /* ** 12/27/06: Not enough data, add the current data to our buffer */ for (q=0; q < (jr_int) buf_io->data_length; q++) { jr_AListNativeSetNewTail (buf_io->data_buffer, buf_io->data_ptr[q], char); } buf_io->data_length = 0; } else { if (jr_AListSize (buf_io->data_buffer) > 0) { /* ** 12/27/06: We've already buffered some of the data, add the rest to the buffer */ leftover_length = desired_string_length - jr_AListSize (buf_io->data_buffer); for (q=0; q < leftover_length; q++) { jr_AListNativeSetNewTail (buf_io->data_buffer, buf_io->data_ptr[q], char); } jr_AListNativeSetNewTail (buf_io->data_buffer, 0, char); buf_io->data_length -= leftover_length; buf_io->data_ptr += leftover_length; string = jr_AListExtractBuffer (buf_io->data_buffer); } else { string = jr_malloc (desired_string_length + 1); memcpy (string, buf_io->data_ptr, desired_string_length); string[desired_string_length] = 0; buf_io->data_length -= desired_string_length; buf_io->data_ptr += desired_string_length; } break; } } status = 0; *string_ref = string; return_status : { } return status; } jr_int jr_BufferedIoRead ( jr_BufferedIoType * buf_io, unsigned jr_int max_data_length, const char ** data_buffer_ref, unsigned jr_int * data_length_ref, char * error_buf) { const char * data_buffer; unsigned jr_int data_length; jr_int status; if (jr_AListSize (buf_io->data_buffer) > 0) { /* ** 9/16/07: Only occurs if GetKnownData() call can't read enough data? */ data_buffer = jr_AListHeadPtr (buf_io->data_buffer); data_length = jr_AListSize (buf_io->data_buffer); jr_AListSetSize (buf_io->data_buffer, 0); } else if (buf_io->data_length > 0) { data_buffer = buf_io->data_ptr; if (max_data_length > 0 && buf_io->data_length > max_data_length) { data_length = max_data_length; buf_io->data_ptr += max_data_length; buf_io->data_length -= max_data_length; } else { data_length = buf_io->data_length; buf_io->data_ptr += buf_io->data_length; buf_io->data_length = 0; } } else if (buf_io->data_length == 0) { status = buf_io->raw_read_fn( buf_io->raw_read_arg, max_data_length, &data_buffer, &data_length, error_buf ); if (status != 0) { goto return_status; } if (max_data_length > 0 && data_length > max_data_length) { buf_io->data_ptr = data_buffer + max_data_length; buf_io->data_length = data_length - max_data_length;; data_length = max_data_length; } } else { jr_esprintf( error_buf, "illegal negative data length %d", buf_io->data_length); status = jr_INTERNAL_ERROR; goto return_status; } status = 0; *data_buffer_ref = data_buffer; *data_length_ref = data_length; return_status : { } return status; } void jr_BufferedIoSetFilePtr( jr_BufferedIoType * buf_io, FILE * rfp) { buf_io->rfp = rfp; if (buf_io->read_buffer) { jr_free( buf_io->read_buffer); } buf_io->read_buffer_length = 8192; buf_io->read_buffer = jr_malloc( buf_io->read_buffer_length); jr_BufferedIoSetRawReadFn( buf_io, jr_BufferedIoFread, buf_io); } jr_int jr_BufferedIoFread( void * raw_read_arg, unsigned jr_int max_data_length, const char ** data_ptr_ref, unsigned jr_int * data_length_ref, char * error_buf) { jr_BufferedIoType * buf_io = raw_read_arg; size_t num_bytes; jr_int status; /* ** 11-29-2011: use read(2) since fread() buffers, i.e. won't return ** until the buffer is full or EOF. */ num_bytes = fread( (char *) buf_io->read_buffer, 1, buf_io->read_buffer_length, buf_io->rfp); if (num_bytes == 0 && ferror( buf_io->rfp)) { jr_esprintf( error_buf, "read error: %s", strerror( errno)); status = jr_INTERNAL_ERROR; goto return_status; } *data_ptr_ref = buf_io->read_buffer; *data_length_ref = (jr_int) num_bytes; status = 0; return_status : { } return status; }
frankjas/libjr
libjr/misc/jr_mime.c
<filename>libjr/misc/jr_mime.c #define _POSIX_SOURCE 1 #include "ezport.h" #include <errno.h> #include "jr/mime.h" #include "jr/malloc.h" #include "jr/error.h" #include "jr/string.h" #include "jr/vector.h" #include "jr/misc.h" void jr_MimeTableInit (mime_table_ptr) jr_MimeTableType * mime_table_ptr; { jr_HTableInit ( mime_table_ptr->str_table, sizeof (jr_MimeInfoType), jr_MimeInfoHash, jr_MimeInfoCmp ); } void jr_MimeTableUndo (mime_table_ptr) jr_MimeTableType * mime_table_ptr; { jr_MimeInfoType * mime_info_ptr; jr_HTableForEachElementPtr (mime_table_ptr->str_table, mime_info_ptr) { jr_MimeInfoUndo (mime_info_ptr); } jr_HTableUndo (mime_table_ptr->str_table); } jr_int jr_MimeTableAddNewElement ( mime_table_ptr, file_ext_str, mime_type_str, file_name, line_number, error_buf ) jr_MimeTableType * mime_table_ptr; const char * file_ext_str; const char * mime_type_str; const char * file_name; jr_int line_number; char * error_buf; { jr_MimeInfoType tmp_mime_info [1]; jr_MimeInfoType * mime_info_ptr; jr_MimeInfoInit (tmp_mime_info, file_ext_str, mime_type_str, file_name, line_number); mime_info_ptr = jr_HTableFindElementPtr (mime_table_ptr->str_table, tmp_mime_info); if (mime_info_ptr) { jr_MimeInfoUndo (tmp_mime_info); if (strcasecmp (jr_MimeInfoMimeTypeString (mime_info_ptr), mime_type_str) == 0) { return 0; } jr_esprintf (error_buf, "'%.64s' (on %.64s:%d)", jr_MimeInfoMimeTypeString (mime_info_ptr), jr_MimeInfoFileName (mime_info_ptr), jr_MimeInfoLineNumber (mime_info_ptr) ); return -1; } jr_HTableSetNewElement (mime_table_ptr->str_table, tmp_mime_info); return 0; } const char *jr_MimeTableFindMimeType( jr_MimeTableType * mime_table_ptr, const char * file_ext_str) { jr_MimeInfoType tmp_mime_info [1]; jr_MimeInfoType * mime_info_ptr; jr_MimeInfoInit (tmp_mime_info, file_ext_str, 0, 0, 0); mime_info_ptr = jr_HTableFindElementPtr (mime_table_ptr->str_table, tmp_mime_info); if (mime_info_ptr) { return jr_MimeInfoMimeTypeString( mime_info_ptr); } return 0; } jr_int jr_MimeTableLoadFromFileName (mime_table_ptr, rfn, mode, error_buf) jr_MimeTableType * mime_table_ptr; char * rfn; jr_int mode; char * error_buf; { FILE * rfp = 0; jr_int status; if (strcmp(rfn, "-") == 0) { status = jr_MimeTableLoadFromFilePtr (mime_table_ptr, stdin, "{stdin}", mode, error_buf) ; if (status != 0) { goto return_status; } } else { rfp = fopen(rfn, "r") ; if (rfp == NULL) { jr_esprintf (error_buf, "couldn't open for reading: %s", strerror (errno) ); status = -1; goto return_status; } status = jr_MimeTableLoadFromFilePtr (mime_table_ptr, rfp, rfn, mode, error_buf) ; if (status != 0) { goto return_status; } fclose(rfp) ; rfp = 0; } status = 0; return_status : { if (rfp) { fclose (rfp); } } return status; } jr_int jr_MimeTableLoadFromFilePtr (mime_table_ptr, rfp, rfn, mode, error_buf) jr_MimeTableType * mime_table_ptr; FILE * rfp; char * rfn; jr_int mode; char * error_buf; { jr_int line_number; char line_buffer [1024]; char * start_ptr; const char ** word_vector = 0; const char * mime_type_str; const char * file_ext_str; jr_int k; jr_int status; for ( line_number = 1; fgets (line_buffer, sizeof (line_buffer), rfp) != NULL; line_number ++) { start_ptr = jr_FirstNonWhiteSpacePtr (line_buffer); if (*start_ptr == jr_MIME_FILE_LINE_COMMENT_CHAR) { continue; } word_vector = jr_VectorCreateWithWords (start_ptr, jr_MIME_FILE_WORD_DELIMITERS); if (jr_VectorLength (word_vector) > 1) { mime_type_str = word_vector [0]; for (k=1; word_vector[k]; k++) { file_ext_str = word_vector[k]; status = jr_MimeTableAddNewElement ( mime_table_ptr, file_ext_str, mime_type_str, rfn, line_number, error_buf ); if (status != 0) { if (mode & jr_MIME_TABLE_FLAG_REDEFINITIONS) { jr_esprintf (error_buf, "%.64s:%d: file ext. (%.16s, %.32s): %.100s", rfn, line_number, file_ext_str, mime_type_str, error_buf ); if (mode & jr_MIME_TABLE_EXIT_ON_ERROR) { goto return_status; } else { fprintf (stderr, "Warning: %18s:%-4d: file ext. (%s, %s) == %s\n", rfn, line_number, file_ext_str, mime_type_str, error_buf ); } } } } } jr_VectorDestroy (word_vector); word_vector = 0; } status = 0; return_status : { if (word_vector) { jr_VectorDestroy (word_vector); } } return status; } void jr_MimeTablePrintForPhp (mime_table_ptr, var_name, indent_str, wfp) jr_MimeTableType * mime_table_ptr; const char * var_name; const char * indent_str; FILE * wfp; { jr_MimeInfoType * mime_info_ptr; jr_int printed_entry = 0; fprintf (wfp, "%s$jr_mime_types = array (\n", indent_str); jr_MimeTableForEachMimeInfoPtr (mime_table_ptr, mime_info_ptr) { if (printed_entry) { fprintf (wfp, ",\n"); } fprintf (wfp, "%s\t'%s' => '%s'", indent_str, jr_MimeInfoFileExtString (mime_info_ptr), jr_MimeInfoMimeTypeString (mime_info_ptr) ); printed_entry = 1; } if (printed_entry) { fprintf (wfp, "\n"); } fprintf (wfp, "%s)\n", indent_str); } void jr_MimeInfoInit (mime_info_ptr, file_ext_str, opt_mime_type_str, opt_file_name, opt_line_number) jr_MimeInfoType * mime_info_ptr; const char * file_ext_str; const char * opt_mime_type_str; const char * opt_file_name; jr_int opt_line_number; { memset (mime_info_ptr, 0, sizeof (*mime_info_ptr)); mime_info_ptr->file_ext_str = jr_strdup (file_ext_str); if (opt_mime_type_str) { mime_info_ptr->mime_type_str = jr_strdup (opt_mime_type_str); } if (opt_file_name) { mime_info_ptr->file_name = jr_strdup (opt_file_name); } mime_info_ptr->line_number = opt_line_number; } void jr_MimeInfoUndo (mime_info_ptr) jr_MimeInfoType * mime_info_ptr; { if (mime_info_ptr->file_ext_str) { jr_free (mime_info_ptr->file_ext_str); } if (mime_info_ptr->mime_type_str) { jr_free (mime_info_ptr->mime_type_str); } if (mime_info_ptr->file_name) { jr_free (mime_info_ptr->file_name); } } jr_int jr_MimeInfoCmp (void_ptr_1, void_ptr_2) const void * void_ptr_1; const void * void_ptr_2; { const jr_MimeInfoType * mime_info_ptr_1 = void_ptr_1; const jr_MimeInfoType * mime_info_ptr_2 = void_ptr_2; jr_int diff; diff = strcasecmp (mime_info_ptr_1->file_ext_str, mime_info_ptr_2->file_ext_str); if (diff != 0) { return diff; } return 0; } jr_int jr_MimeInfoHash (void_ptr_1) const void * void_ptr_1; { const jr_MimeInfoType * mime_info_ptr_1 = void_ptr_1; jr_int hash_value = 0; hash_value += jr_strhash_pjw (mime_info_ptr_1->file_ext_str); return hash_value; }
frankjas/libjr
libjr/missing/sysconf.c
<gh_stars>0 #define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_sysconf_objects #include <errno.h> #include <sys/types.h> #include <unistd.h> /* include something to get NGROUPS and NOFILE and MAXUPRC and NCARGS */ #include <sys/param.h> /* include something to get CLK_TCK */ #include <time.h> long sysconf(desired_value) int desired_value ; { switch(desired_value) { case _SC_ARG_MAX : /* maximum number of bytes total for exec args */ return(NCARGS) ; /* from sys/param.h */ case _SC_CHILD_MAX : /* maximum number of processes per user */ return(MAXUPRC) ; /* from sys/param.h */ case _SC_CLK_TCK : /* number of "ticks" per second measuring execution time */ return(CLK_TCK) ; /* from time.h */ case _SC_NGROUPS_MAX : /* maximum number of groups that one user can be in */ return(NGROUPS) ; /* from sys/param.h */ case _SC_OPEN_MAX : /* maximum number of open file descriptors */ return(NOFILE) ; /* from sys/param.h */ case _SC_JOB_CONTROL : /* does this machine support tcsetpgrp() */ return(_POSIX_JOB_CONTROL) ; /* from unistd.h */ case _SC_SAVED_IDS : /* does this machine "save" the real uid upon setuid calls */ return(_POSIX_SAVED_IDS) ; /* from unistd.h */ case _SC_VERSION : return(_POSIX_VERSION) ; /* from unistd.h */ default : errno = EINVAL ; return(-1) ; } } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/struct/strtab.c
<filename>libjr/struct/strtab.c #include "strtab.h" void jr_StringTableInit (str_table_ptr, user_data_size) jr_StringTableType * str_table_ptr; jr_int user_data_size; { memset (str_table_ptr, 0, sizeof (*str_table_ptr)); if (user_data_size == 0) { /* ** 9/5/2005: Can't set an htable prefix without a data size, ** otherwise the foreach loops miss the last element. */ user_data_size = 4; } jr_HTableInit ( str_table_ptr->string_table, user_data_size, jr_StringTableEntryHash, jr_StringTableEntryCmp ); jr_HTableSetPrefixSize ( str_table_ptr->string_table, sizeof (jr_StringTableEntryType), 0, 0 ); } void jr_StringTableUndo (str_table_ptr) jr_StringTableType * str_table_ptr; { jr_StringTableEntryType * str_entry_ptr; jr_HTableForEachElementPtr (str_table_ptr->string_table, str_entry_ptr) { jr_StringTableEntryUndo (str_entry_ptr - 1); } jr_HTableUndo (str_table_ptr->string_table); } jr_StringTableType *jr_StringTableCreate (user_data_size) jr_int user_data_size; { jr_StringTableType * str_table_ptr; str_table_ptr = jr_malloc (sizeof (jr_StringTableType)); jr_StringTableInit (str_table_ptr, user_data_size); return str_table_ptr; } void jr_StringTableDestroy (str_table_ptr) jr_StringTableType * str_table_ptr; { jr_StringTableUndo (str_table_ptr); jr_free (str_table_ptr); } jr_int jr_StringTableAddNewString (str_table_ptr, new_string) jr_StringTableType * str_table_ptr; const char * new_string; { jr_StringTableEntryType tmp_str_entry [1]; jr_int new_index; jr_StringTableEntryInit (tmp_str_entry, new_string); new_index = jr_HTableFindElementIndex (str_table_ptr->string_table, tmp_str_entry + 1); /* ** 11/1/05: the comp. and hash functions expect a pointer to the end ** of the string table entry. */ if (new_index >= 0) { jr_StringTableEntryUndo (tmp_str_entry); return -(new_index + 1); } new_index = jr_HTableNewElementIndex (str_table_ptr->string_table, tmp_str_entry + 1); /* ** 11/1/05: the comp. and hash functions expect a pointer to the end ** of the string table entry. */ /* ** 9/5/2005: the string table entry is in the element prefix */ memcpy ( jr_StringTablePrefixEntryPtr (str_table_ptr, new_index), tmp_str_entry, sizeof (jr_StringTableEntryType) ); /* ** 9/5/2005: the application data is uninitialized */ return new_index; } jr_int jr_StringTableFindString (str_table_ptr, string) jr_StringTableType * str_table_ptr; const char * string; { jr_StringTableEntryType tmp_str_entry [1]; jr_int string_index; jr_StringTableEntryInit (tmp_str_entry, string); string_index = jr_HTableFindElementIndex (str_table_ptr->string_table, tmp_str_entry + 1); /* ** 11/1/05: the comp. and hash functions expect a pointer to the end ** of the string table entry. */ jr_StringTableEntryUndo (tmp_str_entry); return string_index; } void jr_StringTableEntryInit (str_entry_ptr, string) jr_StringTableEntryType * str_entry_ptr; const char * string; { memset (str_entry_ptr, 0, sizeof (*str_entry_ptr)); str_entry_ptr->string = jr_strdup (string); } void jr_StringTableEntryUndo (str_entry_ptr) jr_StringTableEntryType * str_entry_ptr; { jr_free (str_entry_ptr->string); } jr_int jr_StringTableEntryCmp (void_ptr_1, void_ptr_2) const void * void_ptr_1; const void * void_ptr_2; { const jr_StringTableEntryType * str_entry_ptr_1 = void_ptr_1; const jr_StringTableEntryType * str_entry_ptr_2 = void_ptr_2; jr_int diff; /* ** 9/5/2005: the string table entry is in the element prefix */ str_entry_ptr_1--; str_entry_ptr_2--; diff = strcmp (str_entry_ptr_1->string, str_entry_ptr_2->string); if (diff != 0) { return diff; } return 0; } jr_int jr_StringTableEntryHash (void_ptr) const void * void_ptr; { const jr_StringTableEntryType * str_entry_ptr = void_ptr; jr_int hash_value = 0; /* ** 9/5/2005: the string table entry is in the element prefix */ str_entry_ptr --; hash_value += jr_strhash_pjw (str_entry_ptr->string); return hash_value; }
frankjas/libjr
include/jr/ezport/missing.h
<reponame>frankjas/libjr #ifndef __MISSING_HEADER__ #define __MISSING_HEADER__ /******** Missing Types ********/ #ifdef missing_unix_sys_types typedef jr_short ino_t; typedef jr_short dev_t; typedef jr_int off_t; typedef jr_int uid_t; typedef jr_int gid_t; typedef jr_int pid_t; #endif #ifdef missing_mode_t typedef jr_int mode_t; #endif #ifdef missing_off_t typedef jr_int off_t; #endif #ifdef missing_ssize_type typedef jr_int ssize_t; #endif #ifdef missing_addr_types typedef jr_int daddr_t; typedef char * caddr_t; #endif #ifdef missing_struct_iov struct iovec { void * iov_base; /* Pointer to data. */ size_t iov_len; /* Length of data. */ }; #define APR_IOVEC_DEFINED /* ** 2-28-2013: APR may also add it, turn off the def. in APR header files ** Note won't affect build of APR since that doesn't include this header. */ #endif #ifdef missing_struct_msghdr #include <sys/types.h> struct msghdr { caddr_t msg_name; /* optional address */ jr_int msg_namelen; /* size of address */ struct iovec * msg_iov; /* scatter/gather array */ jr_int msg_iovlen; /* # elements in msg_iov */ caddr_t msg_accrights; /* access rights sent/received */ jr_int msg_accrightslen; }; #endif #ifdef missing_msghdr_accrights_fields # define msg_accrights msg_control # define msg_accrightslen msg_controllen #endif /******** Missing #defines ********/ #ifdef missing_seek_constants # define SEEK_SET 0 # define SEEK_CUR 1 # define SEEK_END 2 #endif #ifdef missing_sigtrap # ifdef vendor_netbsd # if (__version__ <= 1100) # define SIGTRAP 5 /* from <sys/signal.h> */ # endif # endif #endif #ifdef missing_sigiot # define SIGIOT SIGABRT /* according to several sources */ #endif #ifdef missing_sigpwr # define SIGPWR SIGUSR1 #endif /* .bp */ /******** Missing Functions/Macros ********/ #ifdef missing_strerror extern char *sys_errlist []; # define strerror(errnum) (sys_errlist[errnum]) #endif #ifdef missing_ascii_in_ctype # define isascii(c) ((unsigned)(c)<=0177) # define toascii(c) ((int)((c)&0177)) #endif #ifdef missing_strchr extern char *strchr PROTO ((const char *str, int chr)) ; #endif #ifdef missing_strrchr extern char *strrchr PROTO ((const char *str, int chr)) ; #endif #ifdef missing_strstr extern char *strstr PROTO ((const char *str, const char *pat)) ; #endif #ifdef missing_strcasestr extern char *strcasestr PROTO ((const char *str, const char *pat)) ; #endif #ifdef missing_strcasecmp # define missing_strcasecmp_extern #endif #ifdef missing_strncasecmp # define missing_strncasecmp_extern #endif #ifdef missing_strdup # define missing_strdup_extern #endif #ifdef missing_memcpy # define missing_memcpy_extern #endif #ifdef missing_memset # define missing_memset_extern #endif #ifdef missing_putenv extern int putenv PROTO((char * name_equals_value_str)) ; #endif #ifdef missing_wifcore_macro # ifdef ostype_cygwin # define WIFCORE(x) WCOREDUMP(x) # else # define WIFCORE(x) ( (*((int *) &x)) & 0200) # endif #endif /* .bp */ #ifdef missing_bzero # define bzero(s,t,n) memcpy (t,s,n) #endif #ifdef missing_roundf # define roundf(fval) floorf( fval + 0.5) #endif /******** Missing Externs ********/ #ifdef missing_bind_extern # include <sys/types.h> # include <sys/socket.h> extern int bind PROTO ((int socket, struct sockaddr *addr_ptr, int addr_len)); #endif #ifdef missing_byte_order_externs # ifdef has_machine_endian_h # include <machine/endian.h> # else extern unsigned long htonl PROTO ((unsigned long hostlong)); extern unsigned long ntohl PROTO ((unsigned long hostlong)); extern unsigned short htons PROTO ((unsigned short hostshort)); extern unsigned short ntohs PROTO ((unsigned short hostshort)); # endif #endif #ifdef missing_bzero_extern /* * used in macro FD_ZERO */ extern void bzero PROTO ((void *ptr, unsigned int nbytes)); #endif #ifdef missing_connect_extern # include <sys/types.h> # include <sys/socket.h> extern int connect PROTO ((int socket, struct sockaddr *addr_ptr, int addr_len)); #endif #ifdef missing_crypt_extern extern char * crypt PROTO ((const char *key, const char *salt)); #endif #ifdef missing_errno_externs extern int errno ; extern char *sys_errlist []; #endif #ifdef missing_fclose_extern # include <stdio.h> extern int fclose PROTO ((FILE *fp)); #endif #ifdef missing_fflush_extern # include <stdio.h> extern int fflush PROTO ((FILE *fp)); #endif #ifdef missing__filbuf_extern # include <stdio.h> extern int _filbuf PROTO ((FILE *fp)); #endif #ifdef missing_flock_extern extern int flock PROTO ((int fd, int lock_type)); #endif #ifdef missing__flsbuf_extern # include <stdio.h> extern int _flsbuf PROTO ((unsigned int c, FILE *fp)); #endif #ifdef missing_fsync_extern extern int fsync PROTO ((int fd)); #endif #ifdef missing_ftruncate_extern # include <sys/types.h> extern int ftruncate PROTO ((int fd, off_t length)); #endif #ifdef missing_gethostname_extern extern int gethostname PROTO ((char *name_buffer, int max_length)); #endif #ifdef missing_getsockname_extern # include <sys/types.h> # include <sys/socket.h> extern int getsockname PROTO ((int socket, struct sockaddr *addr_ptr, int *addr_len_ptr)); #endif #ifdef missing_getwd_extern extern char * getwd PROTO ((char *pathname)); #endif #ifdef missing_ioctl_extern extern int ioctl PROTO ((int fd, unsigned long request, ...)); #endif #ifdef missing_listen_extern extern int listen PROTO ((int socket, int backlog)); #endif #ifdef missing_memset_extern extern void *memset PROTO (( void *ptr, int value, unsigned long numbytes )) ; #endif #ifdef missing_memcpy_extern extern void *memcpy PROTO (( void *dest, const void *source, unsigned long numbytes )) ; #endif #ifdef missing_memmove_extern extern void *memmove PROTO (( void *dest, const void *source, unsigned long numbytes )) ; #endif #ifdef missing_mktemp_extern extern char * mktemp PROTO ((char *)); #endif #ifdef missing_nx_function_externs extern void NXChangeBuffer PROTO((void * /* NXStream * */)) ; #endif #ifdef missing_perror_extern extern int perror PROTO ((char *message)); #endif #ifdef missing_printf_externs # include <stdio.h> extern int printf PROTO ((const char *format, ...)); extern int fprintf PROTO ((FILE *wfp, const char *format, ...)); extern int sprintf PROTO ((char *str, const char *format, ...)); extern int scanf PROTO ((const char *format, ...)); extern int fscanf PROTO ((FILE *rfp, const char *format, ...)); extern int sscanf PROTO ((const char *str, const char *format, ...)); extern int fseek PROTO ((FILE *fp, long offset, int whence)); extern int fread PROTO ((void *buf, int item_size, int nitems, FILE *fp)); extern int fwrite PROTO ((const void *buf, int item_size, int nitems, FILE *fp)); #endif #ifdef missing_random_extern extern long random PROTO ((void)); #endif #ifdef missing_recvmsg_extern #include <sys/types.h> #include <sys/socket.h> extern int recvmsg PROTO (( int socket_fd, struct msghdr msg[], int flags )); #endif #ifdef missing_rewind_extern # include <stdio.h> extern int rewind PROTO ((FILE *fp)); #endif #ifdef missing_select_extern #include <sys/types.h> #include <sys/time.h> extern int select PROTO (( int num_fds, fd_set * rdfds, fd_set * wrdfs, fd_set * exfds, struct timeval * wait_interval )); #endif #ifdef missing_sendmsg_extern #include <sys/types.h> #include <sys/socket.h> extern int sendmsg PROTO (( int socket_fd, struct msghdr msg[], int flags )); #endif #ifdef missing_setpgrp_extern extern int setpgrp PROTO ((int pid, int pgrp)); #endif #ifdef missing_setvbuf_extern extern int setvbuf PROTO ((FILE *stream, char *buf, int mode, size_t size)); #endif #ifdef missing_shutdown_extern extern int shutdown PROTO ((int fd, int how)); #endif #ifdef missing_socket_extern extern int socket PROTO ((int addr_family, int type, int protocol_family)); #endif #ifdef missing_srandom_extern extern jr_int srandom PROTO ((long)); #endif #ifdef missing_strdup_extern extern char *strdup PROTO ((const char *str)) ; #endif #ifdef missing_strcasecmp_extern extern int strcasecmp PROTO ((const char *str1, const char *str2)); #endif #ifdef missing_strncasecmp_extern extern int strncasecmp PROTO ((const char *str1, const char *str2, size_t n)) ; #endif #ifdef missing_sys_siglist_extern extern char * sys_siglist[]; #endif #ifdef missing_time_extern extern long time PROTO ((long *tloc)); #endif #ifdef missing_truncate_extern # include <sys/types.h> extern int truncate PROTO ((char *pathname, off_t length)); #endif #ifdef missing_ungetc_extern # include <stdio.h> extern int ungetc PROTO ((int c, FILE *fp)); #endif #ifdef missing_utimes_extern # include <sys/time.h> extern int utimes PROTO ((char *file, struct timeval tvp[2])); #endif #ifdef missing_res_query_extern extern int res_query PROTO (( const char * dname, int class, int type, unsigned char * answer, int anslen )); #endif #ifdef missing_dn_skipname_extern extern int dn_skipname PROTO (( const unsigned char * answer_ptr, const unsigned char * answer_end_ptr )); #endif #ifdef missing_backtrace_extern extern int backtrace PROTO ((void **pc_array, int pc_array_size)); #endif #ifdef missing_extra_regex_errors # define REG_EEND -1 # define REG_ESIZE -2 # define REG_ERPAREN -3 #endif #ifdef missing_inet_addr_extern extern unsigned long inet_addr (const char *); #endif #ifdef missing_inet_ntoa_extern extern char *inet_ntoa (unsigned long); #endif #ifdef missing_malloc_usable_size_extern # include <sys/types.h> extern size_t malloc_usable_size (void *ptr); #endif #ifdef missing_apr_is_enobufs_macro # define APR_STATUS_IS_ENOBUFS(status) ((status) == ENOBUFS) #endif #ifdef missing_stdbool_header # if !defined(__bool_true_false_are_defined) && !defined(__cplusplus) # define bool jr_int # define true 1 # define false 0 # endif #endif #ifdef missing_siglist_nsig # ifdef ostype_macosx # define NSIG __DARWIN_NSIG # endif #endif #endif
frankjas/libjr
libjr/syscalls/jr_timestr.c
<gh_stars>0 #include "ezport.h" #include <string.h> #include <time.h> #include <apr-1/apr_time.h> #include "jr/time.h" #include "jr/error.h" extern void jr_TimeInitFromTM ( jr_TimeStruct * time_ptr, struct tm * tm_ptr); extern void jr_TimeToTM ( jr_TimeStruct * time_ptr, struct tm * tm_ptr); extern void jr_TimeToAprTimeExp ( jr_TimeStruct * time_ptr, apr_time_exp_t * tm_ptr); extern void jr_TimeInitFromAprTimeExp ( jr_TimeStruct * time_ptr, apr_time_exp_t * tm_ptr); void jr_TimeInit ( jr_TimeStruct * time_ptr, jr_seconds_t time_seconds) { jr_useconds_t time_useconds = jr_seconds_to_useconds( time_seconds); apr_time_t apr_time = jr_ULongToHost64( time_useconds); apr_time_exp_t tm_value; apr_time_exp_gmt( &tm_value, apr_time); jr_TimeInitFromAprTimeExp (time_ptr, &tm_value); time_ptr->is_gmt = 1; } #ifndef missing_strptime jr_int jr_TimeInitFromString ( jr_TimeStruct * time_ptr, const char * time_string, char * error_buf) { struct tm tm_value; const char * finish_ptr; memset( &tm_value, 0, sizeof(tm_value)); /* ** 4-9-2017: strptime() accepts but doesn't process timezone info */ finish_ptr = strptime (time_string, "%a %b %d %T %Z %Y", &tm_value); if (finish_ptr != 0) { jr_esprintf( error_buf, "can't process timezone"); return jr_MISUSE_ERROR; } finish_ptr = strptime (time_string, "%a, %d %b %Y %T%z", &tm_value); if (finish_ptr != 0) { jr_esprintf( error_buf, "can't process timezone"); return jr_MISUSE_ERROR; } finish_ptr = strptime (time_string, "%a, %d %b %Y %T", &tm_value); if (finish_ptr == 0) { finish_ptr = strptime (time_string, "%a %b %d %T %Y", &tm_value); } if (finish_ptr) { jr_TimeInitFromTM (time_ptr, &tm_value); if (strstr (time_string, "GMT")) { time_ptr->is_gmt = 1; } } return 0; } #endif char *jr_TimeToString ( jr_TimeStruct * time_ptr, char * string, jr_int max_length) { apr_time_exp_t tm_value; apr_size_t str_len; jr_TimeToAprTimeExp (time_ptr, &tm_value); apr_strftime (string, &str_len, max_length, "%a, %d %b %Y %T", &tm_value); if (time_ptr->is_gmt && (jr_int) strlen (string) + 4 + 1 < max_length) { strcat (string, " GMT"); } return string; } jr_int jr_DaysPerMonth [] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; #ifdef missing_apr jr_seconds_t jr_TimeToSecondsUTC ( jr_TimeStruct * time_ptr) { jr_seconds_t seconds; jr_int leapyr ; jr_int year ; leapyr = ((time_ptr->year %4) == 0) ? 1 : 0; year = time_ptr->year - 68 ; seconds = (((year - 2)*365) + ((year - 1)/4)) ; /* ** seconds now equals the number of days since 01/01/1970 ** to the beginning of the year specified */ seconds += jr_DaysPerMonth[time_ptr->month] ; if (leapyr && (time_ptr->month > 1)) { (seconds)++ ; } /* ** seconds now equals the number of days since 01/01/70 ** to the beginning of the year and month specified */ seconds += (time_ptr->month_day - 1) ; /* ** seconds now equals the number of days since 01/01/70 ** to the year month and date specified */ seconds = (seconds * 24L) + time_ptr->hour - ((time_ptr->is_dst)?1:0) ; seconds = (seconds * 60L) + time_ptr->minute ; seconds = (seconds * 60L) + time_ptr->second ; if (! time_ptr->is_gmt) { struct timezone tzs ; struct timeval tvs ; gettimeofday(&tvs,&tzs) ; seconds += tzs.tz_minuteswest * 60; } return seconds; } #else jr_seconds_t jr_TimeToSecondsUTC ( jr_TimeStruct * time_ptr) { apr_time_exp_t tm_value; apr_time_t apr_time; jr_TimeToAprTimeExp (time_ptr, &tm_value); /* ** 4-9-2017: will fail on 12/31/1969 16:00 since jr_Time doesn't ** propogate the gmtoffset */ apr_time_exp_gmt_get( &apr_time, &tm_value); return apr_time/1000000; } #endif void jr_TimeToTM ( jr_TimeStruct * time_ptr, struct tm * tm_ptr) { tm_ptr->tm_sec = time_ptr->second; tm_ptr->tm_min = time_ptr->minute; tm_ptr->tm_hour = time_ptr->hour; tm_ptr->tm_mday = time_ptr->month_day; tm_ptr->tm_mon = time_ptr->month; tm_ptr->tm_year = time_ptr->year; tm_ptr->tm_wday = time_ptr->week_day; tm_ptr->tm_yday = time_ptr->year_day; tm_ptr->tm_isdst = time_ptr->is_dst != 0; } void jr_TimeInitFromTM ( jr_TimeStruct * time_ptr, struct tm * tm_ptr) { memset (time_ptr, 0, sizeof (*time_ptr)); time_ptr->second = tm_ptr->tm_sec; time_ptr->minute = tm_ptr->tm_min; time_ptr->hour = tm_ptr->tm_hour; time_ptr->month_day = tm_ptr->tm_mday; time_ptr->month = tm_ptr->tm_mon; time_ptr->year = tm_ptr->tm_year; time_ptr->week_day = tm_ptr->tm_wday; time_ptr->year_day = tm_ptr->tm_yday; time_ptr->is_dst = tm_ptr->tm_isdst != 0; } void jr_TimeToAprTimeExp ( jr_TimeStruct * time_ptr, apr_time_exp_t * tm_ptr) { memset( tm_ptr, 0, sizeof(* tm_ptr)); tm_ptr->tm_usec = 0; tm_ptr->tm_sec = time_ptr->second; tm_ptr->tm_min = time_ptr->minute; tm_ptr->tm_hour = time_ptr->hour; tm_ptr->tm_mday = time_ptr->month_day; tm_ptr->tm_mon = time_ptr->month; tm_ptr->tm_year = time_ptr->year; tm_ptr->tm_wday = time_ptr->week_day; tm_ptr->tm_yday = time_ptr->year_day; tm_ptr->tm_isdst = time_ptr->is_dst != 0; tm_ptr->tm_gmtoff = time_ptr->gmt_off; } void jr_TimeInitFromAprTimeExp ( jr_TimeStruct * time_ptr, apr_time_exp_t * tm_ptr) { memset (time_ptr, 0, sizeof (*time_ptr)); time_ptr->second = tm_ptr->tm_sec; time_ptr->minute = tm_ptr->tm_min; time_ptr->hour = tm_ptr->tm_hour; time_ptr->month_day = tm_ptr->tm_mday; time_ptr->month = tm_ptr->tm_mon; time_ptr->year = tm_ptr->tm_year; time_ptr->week_day = tm_ptr->tm_wday; time_ptr->year_day = tm_ptr->tm_yday; time_ptr->is_dst = tm_ptr->tm_isdst; time_ptr->gmt_off = tm_ptr->tm_gmtoff; }
frankjas/libjr
libjr/missing/tcpgrp.c
#define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_tcpgrp #include <sys/types.h> #include <unistd.h> #include <sys/ioctl.h> int tcsetpgrp(fd, pgrp) int fd ; pid_t pgrp ; { return ioctl(fd, TIOCSPGRP, &pgrp) ; } pid_t tcgetpgrp(fd) int fd ; { jr_int status ; pid_t pgrp ; status = ioctl(fd, TIOCGPGRP, &pgrp) ; if (status == -1) return(status) ; return(pgrp) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/symtab/st_lib.c
#include "project.h" jr_ST_Identifier *jr_ST_IdentifierCreate (str) char * str; { jr_ST_Identifier * id_ptr; id_ptr = jr_malloc (sizeof(jr_ST_Identifier)); jr_ST_IdentifierInit (id_ptr, str); return id_ptr; } void jr_ST_IdentifierInit (id_ptr, str) jr_ST_Identifier * id_ptr; const char * str; { id_ptr->str = jr_strdup (str); id_ptr->symbol = 0; id_ptr->num_refs = 0; } void jr_ST_IdentifierDestroy (id_ptr) jr_ST_Identifier * id_ptr; { jr_ST_IdentifierUndo (id_ptr); jr_free (id_ptr); } void jr_ST_IdentifierUndo (id_ptr) jr_ST_Identifier * id_ptr; { jr_free (id_ptr->str); } jr_int jr_ST_IdentifierHash (void_arg_1) const void * void_arg_1; { const jr_ST_Identifier * id = void_arg_1; return (jr_strhash (id->str)); } jr_int jr_ST_IdentifierCmp (void_arg_1, void_arg_2) const void * void_arg_1; const void * void_arg_2; { const jr_ST_Identifier * id_1 = void_arg_1; const jr_ST_Identifier * id_2 = void_arg_2; return (strcmp (id_1->str, id_2->str)); } void jr_ST_StringInit (string_info, string) jr_ST_StringType * string_info; char * string; { memset (string_info, 0, sizeof (*string_info)); string_info->string = jr_strdup (string); } void jr_ST_StringUndo (string_info) jr_ST_StringType * string_info; { jr_free (string_info->string); } void jr_ST_StringInitForLookUp (string_info, string) jr_ST_StringType * string_info; char * string; { string_info->string = string; } jr_int jr_ST_StringHash (void_arg_1) const void * void_arg_1; { const jr_ST_StringType * string_info = void_arg_1; jr_int hash_value = 0; hash_value += jr_strhash_pjw (string_info->string); return hash_value; } jr_int jr_ST_StringCmp (void_arg_1, void_arg_2) const void * void_arg_1; const void * void_arg_2; { const jr_ST_StringType * string_info_1 = void_arg_1; const jr_ST_StringType * string_info_2 = void_arg_2; jr_int diff; diff = strcmp (string_info_1->string, string_info_2->string); if (diff != 0) { return diff; } return 0; }
frankjas/libjr
libjr/syscalls/signame.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <signal.h> #include "jr/syscalls.h" extern void jr_sys_siglist_init (); char *jr_SignalName (sig_num) unsigned jr_int sig_num; { const char * sig_list_entry; static char return_buf [32]; # ifdef missing_sys_siglist_objects { if (sys_siglist[SIGINT] == 0) { jr_sys_siglist_init (); } } # endif if (sig_num > 0 && sig_num < NSIG) { sig_list_entry = sys_siglist[sig_num]; if (sig_list_entry) { sprintf (return_buf, "%.31s", sig_list_entry); } else { sprintf (return_buf, "Signal %d", sig_num); } } else { # ifdef ostype_winnt /* ** 2-5-2019: jr_process_wait() calls apr_proc_wait() which calls ** GetExitCodeProcess() which could return 0xc000XXXX as the exception code */ sprintf (return_buf, "%#x", sig_num); # else sprintf (return_buf, "Invalid signal %d", sig_num); # endif } return return_buf; }
frankjas/libjr
libjr/syscalls/jr_mkdir.c
#include "ezport.h" #include <string.h> #include <errno.h> #include <apr-1/apr_pools.h> #include <apr-1/apr_file_io.h> #include "jr/trace.h" #include "jr/syscalls.h" #include "jr/apr.h" #include "jr/malloc.h" #include "jr/error.h" #include "jr/vector.h" jr_int jr_MakeDirectoryPath(orig_pathname, perm_flags, error_buf) const char * orig_pathname ; jr_int perm_flags; char * error_buf ; { apr_fileperms_t apr_perms = jr_PermsToUmaskedAprPerms (perm_flags); char * new_pathname = 0; char * curr_end_ptr; apr_pool_t * apr_pool_ptr = 0; jr_int status ; new_pathname = jr_strdup(orig_pathname) ; curr_end_ptr = new_pathname; while (curr_end_ptr) { curr_end_ptr = strchr (curr_end_ptr + 1, '/'); if (curr_end_ptr) { *curr_end_ptr = 0; } status = jr_PathIsDirectory (new_pathname, error_buf); if (status == jr_NOT_FOUND_ERROR) { jr_apr_initialize(); status = apr_pool_create ((apr_pool_t **) &apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } status = apr_dir_make (new_pathname, apr_perms, apr_pool_ptr) ; if (status != 0) { jr_esprintf(error_buf, "%s", jr_apr_strerror( status, error_buf)) ; status = jr_ConvertAprErrno (status); goto return_status; } } else if (status < 0) { jr_esprintf (error_buf, "couldn't access '%.64s': %s", new_pathname, error_buf); goto return_status; } else if (status == 0) { jr_esprintf (error_buf, "'%.64s' is not a directory", new_pathname); status = jr_INTERNAL_ERROR; goto return_status; } if (curr_end_ptr) { *curr_end_ptr = '/'; } } status = 0; return_status : { if (new_pathname) { jr_free (new_pathname); } if (apr_pool_ptr) { apr_pool_destroy (apr_pool_ptr); } } return(status) ; } #ifdef obsolete__ jr_int jr_MakeDirectoryPath(pathname, perm_flags, error_buf) const char * pathname ; jr_int perm_flags; char * error_buf ; { char * target_dirname ; char * pathlist[128] ; jr_int max = sizeof(pathlist) / sizeof(char *) ; jr_int n ; jr_int i ; jr_int status ; jr_int first_char ; mode_t unix_mode = jr_PermsToUnixMode (perm_flags); target_dirname = jr_strdup(pathname) ; first_char = target_dirname[0] ; n = jr_VectorizeIntoWords(target_dirname, "/\\", pathlist, max) ; if (n == max) { jr_esprintf(error_buf,"too many levels of directories "); for (n--; n >= 0; n--) { jr_free(pathlist[n]) ; } return(-1) ; } status = 0 ; *target_dirname = '\0' ; for (i=0; i < n; i++) { if ((*target_dirname != '\0') || (first_char == '/')) { sprintf(strchr(target_dirname,0), "/%s", pathlist[i]) ; first_char = 0 ; } else { sprintf(strchr(target_dirname,0), "%s", pathlist[i]) ; } if (jr_PathIsDirectory(target_dirname)) { /* nothing needs to happen here */ } else { /* the permissions start out -drwxrwxrwx- but will be reduced by the umask */ status = mkdir(target_dirname, unix_mode) ; if (status != 0) { jr_esprintf(error_buf, "couldn't mkdir ('%.64s'): %s", target_dirname, strerror(errno) ) ; break ; } } } jr_VectorUndo(pathlist) ; jr_free(target_dirname) ; if (status == 0) { if (! jr_PathIsDirectory(pathname)) { jr_esprintf(error_buf, "result not directory : %s", strerror(errno)) ; status = -1 ; } } return(status) ; } #endif /* void main() { char error_buf[1024] ; char * pathname = "users/claspac/tmp_ftp/t1/t2/t3" ; jr_set_trace(jr_malloc_stats) ; if (jr_MakeDirectoryPath(pathname, error_buf) != 0) { fprintf(stderr, "%s\n", error_buf) ; exit(-1) ; } else { fprintf(stdout, "%s : is now a directory.\n", pathname) ; } jr_malloc_stats(stdout, "After MakeDirectoryPath") ; exit(0) ; } */
frankjas/libjr
libjr/string/subvect.c
<gh_stars>0 #include "ezport.h" #include <string.h> #include "jr/malloc.h" #include "jr/vector.h" #include "jr/string.h" #include "jr/trace.h" char * jr_NewStringFromDollarVectorSubstitutions(old_string_arg, env_style_vector) const char * old_string_arg ; char ** env_style_vector ; { char dollar_var_name[512] ; char plain_var_name[512] ; char * rhs_dollar_value_string ; char * new_string ; char * old_string ; jr_int vlen ; jr_int i ; vlen = jr_VectorLength(env_style_vector) ; new_string = old_string = jr_strdup(old_string_arg) ; for (i=0; i < vlen; i++) { sscanf(env_style_vector[i], "%[^=]", plain_var_name) ; sprintf(dollar_var_name, "$%s", plain_var_name) ; rhs_dollar_value_string = (char *) strchr(env_style_vector[i], '=') ; if (! rhs_dollar_value_string) { rhs_dollar_value_string = "" ; } else { rhs_dollar_value_string++ ; /* skip over the '=' to the text of the rhs */ } if (jr_is_trace_at_level(jr_io,1)) { fprintf(stderr, "vector[%d] == '%s'\n", i, env_style_vector[i]) ; fprintf(stderr, "\t sub '%s' with '%s'\n", dollar_var_name, rhs_dollar_value_string) ; } new_string = jr_ReplaceSubByteMatches( old_string, (jr_int) strlen(old_string), dollar_var_name, (jr_int) strlen(dollar_var_name), rhs_dollar_value_string, (jr_int) strlen(rhs_dollar_value_string) ) ; jr_free(old_string) ; old_string = new_string ; } return(new_string) ; }
frankjas/libjr
libjr/io/url_lib.c
<reponame>frankjas/libjr #define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <errno.h> #include <string.h> #include <unistd.h> #include "jr/io.h" #include "jr/inetlib.h" #include "jr/error.h" jr_int jr_URL_VerifyExistence (machine_name, port_number, url_string, error_buf) char * machine_name; jr_int port_number; char * url_string; char * error_buf; { jr_int socket_fd; FILE * wfp; FILE * rfp; char line_buf [256]; char version_string [256]; jr_int request_status; jr_int status; socket_fd = jr_InetConnectToService (machine_name, port_number, error_buf); if (socket_fd < 0) { jr_esprintf (error_buf, "couldn't connect to server: %s", error_buf); return -1; } wfp = fdopen (socket_fd, "w"); if (wfp == NULL) { jr_esprintf (error_buf, "couldn't get network connection: fdopen() failed"); shutdown (socket_fd, jr_ALL_DISALLOW); close (socket_fd); return -1; } rfp = fdopen (socket_fd, "r"); if (rfp == NULL) { jr_esprintf (error_buf, "couldn't get network connection: fdopen() failed"); shutdown (socket_fd, jr_ALL_DISALLOW); close (socket_fd); fclose (wfp); return -1; } status = fprintf (wfp, "GET %s HTTP/1.0\n\n", url_string); if (status < 0) { jr_esprintf (error_buf, "couldn't write remote request: %s", strerror (errno) ); status = -1; goto return_status; } status = fflush (wfp); if (status != 0) { jr_esprintf (error_buf, "couldn't write remote request: %s", strerror (errno) ); status = -1; goto return_status; } errno = 0; if (fgets (line_buf, sizeof (line_buf), rfp) == NULL) { if (errno) { jr_esprintf (error_buf, "no reply from server: %s", strerror (errno) ); } else { jr_esprintf (error_buf, "no reply from server: %s", "unexpected end-of-file" ); } status = -1; goto return_status; } status = sscanf (line_buf, "%s %d", version_string, &request_status); if (status != 2) { jr_esprintf (error_buf, "bad reply format: '%s'", line_buf ); status = -1; goto return_status; } status = request_status; return_status : { shutdown (socket_fd, jr_ALL_DISALLOW); close (socket_fd); /* * Without the close, we may get a SIGPIPE, if the * fclose() needs to flush (which it shouldn't). */ fclose (wfp); fclose (rfp); } return status; }
frankjas/libjr
libjr/dlist/dlist.c
#include "project.h" jr_DList *jr_DListCreate (objsize) jr_int objsize; { jr_DList *ptr = (jr_DList *) jr_malloc (sizeof (jr_DList)); jr_DListInit (ptr, objsize); return (ptr); } void jr_DListInit (list, objsize) jr_DList * list; jr_int objsize; { static jr_int added_prefix_info = 0; if (!added_prefix_info) { added_prefix_info = 1; jr_PrefixAddContainerType ( "jr_DList", jr_DListElementPrefixSize, jr_DListTransformPrefix, jr_DListSetPrefixSize, 0 ); } list->tail = 0; list->head = 0; list->objsize = objsize; list->prefix_size = 0; list->allocates_elements = 0; } void jr_DListDestroy (list) jr_DList *list; { jr_DListEmpty (list); jr_free (list); } void jr_DListUndo (list) jr_DList *list; { jr_DListEmpty (list); } void jr_DListEmpty (list) jr_DList *list; { if (jr_DListAllocatesElements (list)) { void * lep; void * next ; lep = jr_DListHeadPtr(list) ; while (lep) { next = jr_DListNextElementPtr (list,lep) ; jr_DListFreeElement (list, lep); lep = next ; } } list->head = 0; list->tail = 0; } jr_int jr_DListElementPrefixSize (list) jr_DList * list; { return 2 * sizeof (void *); } void jr_DListSetPrefixSize (list, prefix_size) jr_DList * list; jr_int prefix_size; { assert (jr_DListIsEmpty (list)); list->prefix_size = prefix_size; } void *jr_DListAllocateElementWithSize (list, size) jr_DList * list; jr_int size; { char * new; list->allocates_elements = 1; new = jr_malloc (list->prefix_size + 2 * sizeof (void *) + size); return new + list->prefix_size + 2 * sizeof (void *); } void *jr_DListAllocateTmpElementWithSize (list, size) jr_DList * list; jr_int size; { void * new; jr_int old_allocates_elements; old_allocates_elements = list->allocates_elements; new = jr_DListAllocateElementWithSize (list, size); if (old_allocates_elements == 0) { list->allocates_elements = 0; } return new; } void jr_DListFreeElement (list, obj_ptr) jr_DList * list; void * obj_ptr; { if (obj_ptr && list->allocates_elements) { jr_FreeDListElementWithPrefix (obj_ptr, list->prefix_size); } } void *_jr_DListNextElementPtr (list, obj_ptr) jr_DList * list; void * obj_ptr; { return jr_DListNextElementPtr (list, obj_ptr); } void *_jr_DListPrevElementPtr (list, obj_ptr) jr_DList * list; void * obj_ptr; { return jr_DListPrevElementPtr (list, obj_ptr); }
frankjas/libjr
libjr/struct/linebuf.c
<filename>libjr/struct/linebuf.c #include "ezport.h" #include <stdio.h> #include <string.h> #include "jr/malloc.h" #include "jr/linebuf.h" #include "jr/misc.h" void jr_LB_LineBufferInit (line_buffer, max_size, max_lines) jr_LB_LineBuffer * line_buffer; jr_int max_size; jr_int max_lines; { memset (line_buffer, 0, sizeof (*line_buffer)); if (max_size < 256) { max_size = 256; } line_buffer->buffer = jr_malloc (max_size); line_buffer->max_size = max_size; max_lines--; if (max_lines < 1) max_lines = 1; line_buffer->prev_buffers = jr_malloc (max_lines * sizeof(char *)); memset (line_buffer->prev_buffers, 0, max_lines * sizeof(char *)); line_buffer->prev_lines = jr_malloc (max_lines* sizeof(jr_int)); line_buffer->max_lines = max_lines; line_buffer->tab_stops = jr_EnvTabStops (); jr_LB_LineBufferReset (line_buffer, 1); } void jr_LB_LineBufferReset (line_buffer, line) jr_LB_LineBuffer * line_buffer; jr_int line; { line_buffer->line = line; line_buffer->column = 0; line_buffer->buffer [0] = 0; { jr_int i; for (i=0; i < line_buffer->max_lines; i++) { line_buffer->prev_lines [i] = 0; if (line_buffer->prev_buffers [i]) { jr_free (line_buffer->prev_buffers [i]); line_buffer->prev_buffers [i] = 0; } } } } void jr_LB_LineBufferUndo (line_buffer) jr_LB_LineBuffer * line_buffer; { jr_LB_LineBufferReset (line_buffer, 0); jr_free (line_buffer->buffer); jr_free (line_buffer->prev_buffers); jr_free (line_buffer->prev_lines); } /* * both line and column can be negative or less than * the current position. In these cases they will be * ignored and the str appended with one space * separating it from the previous addition */ void jr_LB_AddString (line_buffer, str, line, desired_column) jr_LB_LineBuffer * line_buffer; char * str; jr_int line; jr_int desired_column; { jr_int add_space = 0; if (line < line_buffer->line) { /* * ignore line number less than the current */ line = line_buffer->line; } if (line > line_buffer->line) { jr_LB_SetCurrentLine (line_buffer, line); } if (desired_column <= line_buffer->column) { /* * The column info is messed up. This means * we need to put a space before the str if * there isn't one already */ if ( line_buffer->column > 0 && line_buffer->buffer [line_buffer->column - 1] != ' ') { jr_LB_AddChar (line_buffer, ' '); } desired_column = jr_LB_CurrentColumn (line_buffer) + 1; add_space = 1; } /* * add blanks between end of line and column */ /* Will changed to be easier for debug analysis */ { jr_int num_blanks_needed ; jr_int i ; num_blanks_needed = desired_column - (jr_LB_CurrentColumn(line_buffer) + 1); for (i=0; i < num_blanks_needed; i++) { jr_LB_AddChar (line_buffer, ' ') ; } } { jr_int i; for (i=0; str[i]; i++) { jr_LB_AddChar (line_buffer, str[i]); } } /* * put a space after since an adjacent column on the next * str might cause words to run together */ if (add_space) { jr_LB_AddChar (line_buffer, ' '); } } void jr_LB_AddChar (line_buffer, c) jr_LB_LineBuffer * line_buffer; jr_int c; { if (c == '\t') { jr_int spaces_to_tab_stop; jr_int i; spaces_to_tab_stop = line_buffer->tab_stops - line_buffer->column % line_buffer->tab_stops; for (i=0; i < spaces_to_tab_stop; i++) { jr_LB_AddChar (line_buffer, ' '); } } else { if (line_buffer->column < line_buffer->max_size - 1) { line_buffer->buffer [line_buffer->column] = c; line_buffer->column ++; line_buffer->buffer [line_buffer->column] = 0; } } } void jr_LB_SetPreviousLine (line_buffer, line, buffer) jr_LB_LineBuffer * line_buffer; jr_int line; char * buffer; { jr_int line_index = line % line_buffer->max_lines; line_buffer->prev_lines [line_index] = line; if (line_buffer->prev_buffers [line_index]) { jr_free (line_buffer->prev_buffers [line_index]); line_buffer->prev_buffers [line_index] = 0; } if (buffer) { line_buffer->prev_buffers [line_index] = jr_strdup (buffer); } } void jr_LB_SetCurrentColumn (line_buffer, column) jr_LB_LineBuffer * line_buffer; jr_int column; { if (column < line_buffer->max_size) { line_buffer->column = column; line_buffer->buffer[column] = 0; } } void jr_LB_SetCurrentLine (line_buffer, line) jr_LB_LineBuffer * line_buffer; jr_int line; { if (line > line_buffer->line) { /* * for every line in between, put in an empty line */ jr_int i, first_line, line_index; if (line - line_buffer->line > line_buffer->max_lines) { /* * skipping ahead past what we can record */ first_line = line - line_buffer->max_lines; } else { /* * put the current line in the prev line buffer */ jr_LB_SetPreviousLine (line_buffer, line_buffer->line, line_buffer->buffer); first_line = line_buffer->line + 1; } for (i = first_line; i < line; i++) { line_index = i % line_buffer->max_lines; line_buffer->prev_lines [line_index] = i; if (line_buffer->prev_buffers [line_index]) { jr_free (line_buffer->prev_buffers [line_index]); line_buffer->prev_buffers [line_index] = 0; } } line_buffer->line = line; line_buffer->column = 0; line_buffer->buffer [0] = 0; return; } if (line < line_buffer->line) { jr_int line_index = line % line_buffer->max_lines; jr_int current_line = line_buffer->line; jr_int i; if (line_buffer->prev_lines [line_index] != line) { /* * line not in previous lines */ jr_LB_LineBufferReset (line_buffer, line); return; } /* * restore line from previous lines */ strcpy (line_buffer->buffer, line_buffer->prev_buffers [line_index]); line_buffer->line = line; line_buffer->column = (jr_int) strlen (line_buffer->prev_buffers [line_index]); /* * null out later lines */ for (i = line; i < current_line; i++) { line_index = i % line_buffer->max_lines; line_buffer->prev_lines [line_index] = 0; if (line_buffer->prev_buffers [line_index]) { jr_free (line_buffer->prev_buffers [line_index]); line_buffer->prev_buffers [line_index] = 0; } } return; } } void jr_LB_LineBufferCopy (dest, src) jr_LB_LineBuffer * dest; jr_LB_LineBuffer * src; { jr_int i; dest->line = src->line; if (src->column > dest->max_size - 1) { dest->column = dest->max_size - 1; } else { dest->column = src->column; } strncpy (dest->buffer, src->buffer, dest->max_size - 1); dest->buffer[dest->max_size - 1] = 0; for (i=0; i < src->max_lines && i < dest->max_lines; i++) { jr_LB_SetPreviousLine (dest, src->prev_lines[i], src->prev_buffers[i]); } for (; i < dest->max_lines; i++) { jr_LB_SetPreviousLine (dest, 0, 0); } } char *jr_LB_sprint_lines (str, line_buffer, start_line, end_line, number_format) char * str; jr_LB_LineBuffer * line_buffer; jr_int start_line; jr_int end_line; char * number_format; { char *ret_str = str; jr_int first_index, first_line, line; jr_int i, index; /* * The buffer hasn't caught up to start_line yet */ if (line_buffer->line < start_line) { *str = 0; return (str); } /* * end line == 0 means from start to current line */ if (end_line == 0) end_line = line_buffer->line; /* * find the first line in the buffer */ first_index = line_buffer->line % line_buffer->max_lines; first_line = 0; for (i = 0; i < line_buffer->max_lines; i++) { index = (first_index + i) % line_buffer->max_lines; first_line = line_buffer->prev_lines[index]; if (first_line) break; } if (!first_line) first_line = line_buffer->line; /* * The buffer has passed end_line by */ if (first_line > end_line) { *str = 0; return (str); } /* * find the intersection of the interval passed in * and the interval in the buffer */ if (start_line < first_line) start_line = first_line; if (end_line > line_buffer->line) end_line = line_buffer->line; /* * start line is in the buffer, but could be the current line * similarly for end line * all lines between are in buffer */ for (line = start_line; line <= end_line; line++) { if (line == line_buffer->line) break; index = line % line_buffer->max_lines; if (number_format) { sprintf (str, number_format, line_buffer->prev_lines [index]); str += strlen (str); } if (line_buffer->prev_buffers [index]) { strcpy (str, line_buffer->prev_buffers [index]); str += strlen (line_buffer->prev_buffers [index]); } *str++ = '\n'; } if (end_line == line_buffer->line) { if (number_format) { sprintf (str, number_format, line_buffer->line); str += strlen (str); } strcpy (str, line_buffer->buffer); str += strlen (line_buffer->buffer); *str++ = '\n'; } /* * null out the new line */ str[-1] = 0; return (ret_str); }
frankjas/libjr
libjr/missing/strdup.c
<filename>libjr/missing/strdup.c #define _POSIX_SOURCE 1 #include "ezport.h" #include <stdlib.h> #include <string.h> #ifdef missing_strdup char * strdup(str) const char * str ; { char * result = malloc(strlen(str) + 1) ; strcpy(result, str) ; return(result) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/struct/ptrmap.h
#ifndef _ptrmap_h___ #define _ptrmap_h___ #define _POSIX_SOURCE 1 #include "ezport.h" #include "jr/malloc.h" #include "jr/ptrmap.h" extern void jr_PtrCategoryInit PROTO (( jr_PtrCategoryType * ptr_category, jr_int min_value, jr_int num_values, jr_int ptr_data_size )); extern void jr_PtrCategoryUndo PROTO (( jr_PtrCategoryType * ptr_category )); extern jr_int jr_PtrCategoryOpenPtr PROTO (( jr_PtrCategoryType * ptr_category, void * ptr_value, const char * file_name, jr_int line_number )); #define jr_PtrCategoryNextDeletedDesc(ptr_category, ptr_desc) \ (jr_PtrCategoryPtrInfo (ptr_category, ptr_desc)->next_deleted_desc) #define jr_PtrCategorySetPtrValue(ptr_category, ptr_desc, v) \ (jr_PtrCategoryPtrInfo (ptr_category, ptr_desc)->ptr_value = (v)) #define jr_PtrCategorySetNextDeletedDesc(ptr_category, ptr_desc, v) \ (jr_PtrCategoryPtrInfo (ptr_category, ptr_desc)->next_deleted_desc = (v)) extern void jr_PtrInfoInit PROTO (( jr_PtrInfoStruct * ptr_info, void * ptr_value, const char * file_name, jr_int line_number )); #endif
frankjas/libjr
libjr/misc/jr_base64.c
#include "ezport.h" #include <apr-1/apr_base64.h> #include "jr/misc.h" jr_int jr_base64_encode ( char * encoded_dest, const char * plain_src, jr_int plain_src_length) { jr_int status; status = apr_base64_encode (encoded_dest, plain_src, plain_src_length); return status; } jr_int jr_base64_encode_binary ( char * encoded_dest, const unsigned char * plain_src, jr_int plain_src_length) { jr_int status; status = apr_base64_encode_binary (encoded_dest, plain_src, plain_src_length); return status; }
frankjas/libjr
libjr/syscalls/opendir.c
#include "jr_apr.h" void jr_dir_init ( jr_dir_t * dir_info) { memset (dir_info, 0, sizeof (jr_dir_t)); jr_apr_initialize(); } void jr_dir_undo ( jr_dir_t * dir_info) { jr_dir_close (dir_info); } jr_int jr_dir_open ( jr_dir_t * dir_info, const char * path, char * error_buf) { jr_int status; if (dir_info->apr_pool_ptr == 0) { status = apr_pool_create ((apr_pool_t **) &dir_info->apr_pool_ptr, NULL); if (status != 0) { jr_esprintf (error_buf, "couldn't create pool: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } status = apr_dir_open ((apr_dir_t **) &dir_info->apr_dir_ptr, path, dir_info->apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status: { } return status; } void jr_dir_close ( jr_dir_t * dir_info) { if (dir_info->apr_dir_ptr) { apr_dir_close (dir_info->apr_dir_ptr); dir_info->apr_dir_ptr = 0; } if (dir_info->apr_pool_ptr) { apr_pool_destroy (dir_info->apr_pool_ptr); dir_info->apr_pool_ptr = 0; } } jr_int jr_dir_read ( jr_dir_t * dir_info, const char ** opt_entry_name_ref, struct jr_stat * opt_stat_info, char * error_buf) { apr_finfo_t apr_finfo[1]; jr_int info_bits = 0; jr_int status; unsigned finfo_norm_bits = APR_FINFO_NORM; # ifdef ostype_winnt finfo_norm_bits &= ~(APR_FINFO_IDENT | APR_FINFO_OWNER); # endif if (opt_entry_name_ref) { info_bits |= APR_FINFO_NAME; } if (opt_stat_info) { info_bits |= APR_FINFO_NORM; } status = apr_dir_read (apr_finfo, info_bits, dir_info->apr_dir_ptr); if (status != 0) { if (APR_STATUS_IS_INCOMPLETE (status)) { if (opt_entry_name_ref && (apr_finfo->valid & APR_FINFO_NAME) != APR_FINFO_NAME) { jr_esprintf (error_buf, "can't get dir. entry name"); status = jr_INTERNAL_ERROR; goto return_status; } if (opt_stat_info && (apr_finfo->valid & finfo_norm_bits) != finfo_norm_bits) { jr_esprintf (error_buf, "can't get dir. entry info (valid %#x, norm %#x", apr_finfo->valid, finfo_norm_bits ); status = jr_INTERNAL_ERROR; goto return_status; } /* ** 1/1/07: else we got what we needed. */ } else { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } } if (opt_entry_name_ref) { *opt_entry_name_ref = apr_finfo->name; } if (opt_stat_info) { jr_stat_init (opt_stat_info); jr_stat_asgn_apr_finfo (opt_stat_info, apr_finfo); } status = 0; return_status : { } return status; }
frankjas/libjr
libjr/string/remdupl.c
#include "ezport.h" #include <stdio.h> #include <ctype.h> void jr_RemoveContiguousDuplicateChar(s, c) char * s ; jr_int c ; { char *t=s, *f=s ; for(; *f; ) { *t++ = *f++ ; if ((f[-1] == c) && (f[0] == c)) { f++ ; } } *t = '\0' ; } /* void main() { char result[128] ; char * original = "//f//fline 100002hello 12345 there 6" ; strcpy(result, original) ; jr_RemoveContiguousDuplicateChar(result, '/') ; fprintf(stdout, "jr_RemoveContiguousDuplicateChar('%s', '/') == %s\n", original, result ) ; exit(0) ; } */
frankjas/libjr
libjr/struct/circbuf.c
<filename>libjr/struct/circbuf.c #include "ezport.h" #include <stdio.h> #include <string.h> #include "jr/malloc.h" #include "jr/circbuf.h" void jr_CB_CircularBufferInit (buffer, max_elements, element_size) jr_CB_CircularBuffer *buffer; jr_int max_elements; jr_int element_size; { memset (buffer, 0, sizeof (*buffer)); buffer->element_array = jr_malloc (max_elements * element_size); buffer->max_size = max_elements * element_size; buffer->element_size = element_size; buffer->head = buffer->element_array; buffer->tail = buffer->element_array; buffer->size = 0; buffer->num_elements = 0; } void jr_CB_CircularBufferUndo (buffer) jr_CB_CircularBuffer *buffer; { jr_free (buffer->element_array); } void jr_CB_CircularBufferReset (buffer) jr_CB_CircularBuffer *buffer; { jr_int i; char *element; element = buffer->head; for (i=0; i < buffer->num_elements; i++, element += buffer->element_size) { if (element == buffer->element_array + buffer->max_size) { element = buffer->element_array; } } buffer->head = buffer->element_array; buffer->tail = buffer->element_array; buffer->size = 0; buffer->num_elements = 0; } void *jr_CB_SetNewTail (buffer, element, bumped_element) jr_CB_CircularBuffer *buffer; void *element; void *bumped_element; { void *return_value; if (buffer->size == buffer->max_size) { /* make room for the new entry */ if (bumped_element) { memcpy (bumped_element, buffer->head, buffer->element_size); } buffer->head += buffer->element_size; if (buffer->head == buffer->element_array + buffer->max_size) { buffer->head = buffer->element_array; } return_value = bumped_element; } else { buffer->size += buffer->element_size; buffer->num_elements ++; return_value = 0; } memcpy (buffer->tail, element, buffer->element_size); buffer->tail += buffer->element_size; if (buffer->tail == buffer->element_array + buffer->max_size) { buffer->tail = buffer->element_array; } return (return_value); } void *jr_CB_SetNewHead (buffer, element, bumped_element) jr_CB_CircularBuffer *buffer; void *element; void *bumped_element; { void *return_value; if (buffer->size == buffer->max_size) { /* make room for the new entry */ buffer->tail -= buffer->element_size; if (buffer->tail < buffer->element_array) { buffer->tail = buffer->element_array + buffer->max_size; } if (bumped_element) { memcpy (bumped_element, buffer->tail, buffer->element_size); } return_value = bumped_element; } else { buffer->size += buffer->element_size; buffer->num_elements ++; return_value = 0; } buffer->head -= buffer->element_size; if (buffer->head < buffer->element_array) { buffer->head = buffer->element_array + buffer->max_size - buffer->element_size; } memcpy (buffer->head, element, buffer->element_size); return (return_value); } void jr_CB_GetHead (buffer, element) jr_CB_CircularBuffer *buffer; void *element; { buffer->size -= buffer->element_size; buffer->num_elements --; if (element) { memcpy (element, buffer->head, buffer->element_size); } buffer->head += buffer->element_size; if (buffer->head == buffer->element_array + buffer->max_size) { buffer->head = buffer->element_array; } } void jr_CB_GetTail (buffer, element) jr_CB_CircularBuffer *buffer; void *element; { buffer->size -= buffer->element_size; buffer->num_elements --; buffer->tail -= buffer->element_size; if (buffer->tail < buffer->element_array) { buffer->tail = buffer->element_array + buffer->max_size - buffer->element_size; } if (element) { memcpy (element, buffer->tail, buffer->element_size); } } void *jr_CB_ElementPtr (buffer, i) jr_CB_CircularBuffer *buffer; jr_int i; { i *= buffer->element_size; i += buffer->head - buffer->element_array; if (i >= buffer->max_size) { i -= buffer->max_size; } return (buffer->element_array + i); } void Getjr_CB_ElementPtr (buffer, i, element) jr_CB_CircularBuffer *buffer; jr_int i; void *element; { i *= buffer->element_size; i += buffer->head - buffer->element_array; if (i >= buffer->max_size) { i -= buffer->max_size; } memcpy (element, buffer->element_array + i, buffer->element_size); }
frankjas/libjr
libjr/syscalls/jr_time.c
<reponame>frankjas/libjr #define _POSIX_SOURCE 1 #include "ezport.h" #include <apr-1/apr_time.h> #include "jr/time.h" jr_seconds_t jr_time_seconds () { apr_time_t curr_time; curr_time = apr_time_now (); return apr_time_sec (curr_time); } jr_int jr_time_gmt_offset() { apr_time_t curr_time; apr_time_exp_t curr_time_exp; jr_int status; curr_time = apr_time_now (); status = apr_time_exp_lt( &curr_time_exp, curr_time); if (status == APR_SUCCESS) { return curr_time_exp.tm_gmtoff; } return 0; } jr_useconds_t jr_time_useconds () { apr_time_t curr_time; jr_ULong tmp_ulong; curr_time = apr_time_now (); jr_ULongAsgn64( &tmp_ulong, curr_time ); return tmp_ulong; } char *jr_ctime ( jr_seconds_t curr_time, char * buf) { apr_time_t tmp_time; if (curr_time < 0) { curr_time = jr_time_seconds(); } tmp_time = apr_time_from_sec (curr_time); apr_ctime (buf, tmp_time); return buf; } unsigned jr_int jr_useconds_to_seconds ( jr_useconds_t useconds) { jr_ULong tmp_ulong; jr_ULongDivideUInt( &tmp_ulong, useconds, 1000000 ); if (jr_ULongIsUInt( tmp_ulong )) { return jr_ULongLSW( tmp_ulong ); } return jr_UINT_MAX; } jr_useconds_t jr_seconds_to_useconds( jr_seconds_t seconds) { jr_useconds_t useconds; jr_ULongAsgnUInt (&useconds, seconds); jr_ULongMultUInt (&useconds, useconds, 1000000); return useconds; } void jr_useconds_init ( jr_useconds_t * interval_ptr, unsigned jr_int seconds, unsigned jr_int useconds) { jr_ULongAsgnUInt (interval_ptr, seconds); jr_ULongMultUInt (interval_ptr, *interval_ptr, 1000000); jr_ULongAddUInt (interval_ptr, *interval_ptr, useconds); } void jr_useconds_subtract( jr_useconds_t * dest_ref, jr_useconds_t v1, jr_useconds_t v2) { if (jr_ULongCmp( v1, v2) < 0) { jr_useconds_init( dest_ref, 0, 0); } else { jr_ULongSubtract( dest_ref, v1, v2); } }
frankjas/libjr
libjr/syscalls/async_io.h
#ifndef _jr_async_io_h___ #define _jr_async_io_h___ #define _POSIX_SOURCE 1 #include "ezport.h" #include <signal.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <sys/file.h> #include <sys/time.h> #include <sys/types.h> #include "jr/error.h" #include "jr/io.h" #include "jr/htable.h" extern jr_int jr_AddAsyncIOHandler PROTO (( jr_int fd, FILE * fp, void (*handler_fn) (), void * handler_param, jr_int is_for_reading, char * error_buf )); extern void jr_RemoveAsyncIOHandler PROTO (( jr_int fd, jr_int is_for_reading )); extern void jr_AsyncIOHandler PROTO (( jr_int sig_number )); typedef struct { jr_int fd; FILE * fp; void (*handler_fn) (); void * handler_param; jr_int is_for_reading; } jr_AsyncInfoStruct; extern void jr_AsyncInfoInit PROTO (( jr_AsyncInfoStruct * handler_info, jr_int fd, FILE * fp, void (*handler_fn) (), void * handler_param, jr_int is_for_reading )); extern void jr_AsyncInfoUndo PROTO (( jr_AsyncInfoStruct * handler_info )); extern jr_int jr_AsyncInfoHash PROTO (( const void * void_arg_1 )); extern jr_int jr_AsyncInfoCmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); #endif
frankjas/libjr
libjr/syscalls/jr_chdir.c
#include "ezport.h" #include <stdio.h> #ifdef ostype_winnt # include <windows.h> # include <stdlib.h> #else # include <unistd.h> # include <string.h> # include <errno.h> #endif #include "jr/syscalls.h" #include "jr/error.h" #ifdef ostype_winnt jr_int jr_chdir ( const char * dir_path, char * error_buf) { wchar_t wpath_buf[ MAX_PATH+1]; size_t num_converted_chars; jr_int status; status = mbstowcs_s( &num_converted_chars, wpath_buf, sizeof( wpath_buf) / sizeof( wchar_t), dir_path, _TRUNCATE ); if (status != 0) { jr_esprintf (error_buf, "%s", strerror(status)); goto return_status; } if (! SetCurrentDirectoryW( wpath_buf)) { status = GetLastError(); jr_esprintf (error_buf, "%s", strerror(status)); status = jr_ConvertLastError( status); goto return_status; } return_status : { } return status; } #else jr_int jr_chdir ( const char * dir_path, char * error_buf) { jr_int status; status = chdir (dir_path); if (status != 0) { jr_esprintf (error_buf, "%s", strerror (errno)); return jr_ConvertErrno (errno); } return 0; } #endif