1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "securecutil.h"
17
SecTrimCRLF(char * buffer,const size_t len)18 static void SecTrimCRLF(char *buffer, const size_t len)
19 {
20 int i;
21 for (i = (int)(len - 1); i >= 0 && (buffer[i] == '\r' || buffer[i] == '\n'); --i) {
22 buffer[i] = '\0';
23 }
24 return;
25 }
26
27 /*******************************************************************************
28 * <FUNCTION DESCRIPTION>
29 * The gets_s function reads at most one less than the number of characters
30 * specified by destMax from the stream pointed to by stdin, into the array pointed to by buffer
31 * The line consists of all characters up to and including
32 * the first newline character ('\n'). gets_s then replaces the newline
33 * character with a null character ('\0') before returning the line.
34 * If the first character read is the end-of-file character, a null character
35 * is stored at the beginning of buffer and NULL is returned.
36 *
37 * <INPUT PARAMETERS>
38 * buffer Storage location for input string.
39 * numberOfElements The size of the buffer.
40 *
41 * <OUTPUT PARAMETERS>
42 * buffer is updated
43 *
44 * <RETURN VALUE>
45 * buffer Successful operation
46 * NULL Improper parameter or read failure
47 *******************************************************************************
48 */
gets_s(char * buffer,size_t numberOfElements)49 char *gets_s(char *buffer, size_t numberOfElements)
50 {
51 size_t len;
52 #ifdef SECUREC_COMPATIBLE_WIN_FORMAT
53 size_t bufferSize = ((numberOfElements == (size_t)-1) ? SECUREC_STRING_MAX_LEN : numberOfElements);
54 #else
55 size_t bufferSize = numberOfElements;
56 #endif
57
58 if (buffer == NULL || bufferSize == 0 || bufferSize > SECUREC_STRING_MAX_LEN) {
59 SECUREC_ERROR_INVALID_PARAMTER("gets_s");
60 return NULL;
61 }
62
63 if (fgets(buffer, (int)bufferSize, stdin) == NULL) {
64 return NULL;
65 }
66
67 len = strlen(buffer);
68 if (len > 0 && len < bufferSize) {
69 SecTrimCRLF(buffer, len);
70 }
71
72 return buffer;
73 }
74
75